ASP.NET定时执行时使用Cache防止ASP.NET进程自动回收

在ASP.NET中不管是使用后台进程还是使用Timer的方式都避免不了一个问题,就是ASP.NET会过一段时间后就回收了进程,而不管你后台有没有工作。只有当你再次请求该站点时它才会再次被执行。

我们可以测试一下,Global的APPLICATION_START事件中启动一个Timer第隔5秒钟向文件里写入一个时间,然后你启运这个首页,然后关掉,就会发现过一会儿它就不再向文件里写入内容了。(这个测试的代码上网有很多,这里就不提供代码了)。

为了解决这个问题,我们可以在Global中使用不断刷新Cache的来模拟一个请求,当Cache失效时系统自动请求一个指定的唤醒页面,这样子就模拟了一次请求,使你的应用程序永远处在运行的状态中。

    public class Global : System.Web.HttpApplication
    {        
        const string DummyCacheItemKey = "DummyCacheItem";
        const string DummyPageUrl = "/RaiseUp.aspx";

        protected void Application_Start(object sender, EventArgs e)
        {
            AlwaysRun();
        }

        /// <summary>
        /// 使用Cache过期技术使应用程序永远在线
        /// </summary>
        private void AlwaysRun()
        {
            if(null != HttpContext.Current.Cache[DummyCacheItemKey]) return;

            HttpContext.Current.Cache.Add(DummyCacheItemKey, String.Empty, null,
                DateTime.MaxValue, TimeSpan.FromMinutes(1), System.Web.Caching.CacheItemPriority.Normal,
                new System.Web.Caching.CacheItemRemovedCallback((x, y, z) => new System.Net.WebClient().DownloadData("HTTP://" + Request.Url.Authority + DummyPageUrl)));
        }

        protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            if (HttpContext.Current.Request.Url.AbsolutePath == DummyPageUrl)
                AlwaysRun();
        }
    }

  

posted @ 2011-09-17 11:50  碧玉软件  阅读(879)  评论(0编辑  收藏  举报