你是否曾经打开你的一个网站在你最后显示网页的时候总要等待一段时间,你如果你遇到这个问题,你常常认为是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(
nullnull); 

    
//增加动作到缓存中
    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请求给我们的网站,是网站始终保持激活中。是不是很简单呢:)

 

 

相关文章:

  • 2021-12-29
  • 2021-04-04
  • 2022-12-23
  • 2022-12-23
  • 2021-07-16
  • 2021-11-02
  • 2021-12-04
  • 2021-06-24
猜你喜欢
  • 2021-12-06
  • 2022-03-05
  • 2022-12-23
  • 2022-02-06
  • 2021-10-13
  • 2021-12-27
相关资源
相似解决方案