gdx 发表于 2015-8-13 07:40:59

保持你的网站激活(不要让IIS回收您的网站)

  你是否曾经打开你的一个网站在你最后显示网页的时候总要等待一段时间,你如果你遇到这个问题,你常常认为是IIS引起的,IIS在不断的回收利用网站资源。其实还有一种方法就是让网站不要“闲”下来,看以下代码:

代码

private static void _SetupRefreshAction() {
    //移除之前的动作
    Action remove = HttpContext.Current.Cache["Refresh"] as Action;
    if (remove is Action) {
      HttpContext.Current.Cache.Remove("Refresh");
      remove.EndInvoke(null);
    }
    //获取新的动作

    Action work = () => {
      while (true) {
            Thread.Sleep(60000);
            //这里代码开始刷新动作

      }
    };
    work.BeginInvoke(null, null);
    //增加动作到缓存中
    HttpContext.Current.Cache.Add(
      "Refresh",
      work,
      null,
      Cache.NoAbsoluteExpiration,
      Cache.NoSlidingExpiration,
      CacheItemPriority.Normal,
      (s, o, r) => { _SetupRefreshAction(); }
      );
}
  
  把这段代码写在Global.asax的Application_Start(),这样我们开始一个动作时候让网站保持激活,当然你也可以使用Thread来保持这个刷新方法。
  那么,该怎么保持网站的刷新呢?使用WebClient即可实现:


WebClient refresh = new WebClient();
try {
    refresh.UploadString("http://www.mysite.com/", string.Empty);
}
catch (Exception ex) {
}
finally {
    refresh.Dispose();
}  这个代码片段使用WebClient发生红HTTP请求给我们的网站,是网站始终保持激活中。是不是很简单呢:)
  
  
页: [1]
查看完整版本: 保持你的网站激活(不要让IIS回收您的网站)