问题:Timer不能持续执行,如果长时间没有访问,就会被IIs自动回收。造成一些定时作业无法完成。
解决方案:1。可以单独写一个服务程序。
2。直接在Gloal.aspx的Application_End事件中添加如下代码:
//下面的代码是关键,可解决IIS应用程序池自动回收的问题
Thread.Sleep(1000);
//这里设置你的web地址,可以随便指向你的任意一个aspx页面甚至不存在的页面,目的是要激发Application_Start
string url = "http://localhost/autothreadpool.aspx";
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
Stream receiveStream = Response.GetResponseStream();//得到回写的字节流
经过测试这种方法并不能很有效的解决IIS应用程序池自动回收的问题。
下面给出一种有效的方法:
private const string DummyPageUrl = "http://localhost/Index.aspx";//可访问的页面
private const string DummyCacheItemKey = "Du";
// 注册一缓存条目在5分钟内到期,到期后触发的调事件
private void RegisterCacheEntry()
{
if (null != HttpContext.Current.Cache[DummyCacheItemKey]) return;
HttpContext.Current.Cache.Add(DummyCacheItemKey, "Test", null, DateTime.MaxValue,
TimeSpan.FromMinutes(5), CacheItemPriority.NotRemovable,
new CacheItemRemovedCallback(CacheItemRemovedCallback));
}
// 缓存项过期时程序模拟点击页面,阻止应用程序结束
public void CacheItemRemovedCallback(string key, object value, CacheItemRemovedReason reason)
{
HitPage();
}
// 模拟点击网站网页
private void HitPage()
{
System.Net.WebClient client = new System.Net.WebClient();
client.DownloadData(DummyPageUrl);
}
protected void Application_BeginRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.Request.Url.ToString() == DummyPageUrl)
{
RegisterCacheEntry();
}
}
protected void Application_Start(object sender, EventArgs e)
{
RegisterCacheEntry();
}