代码之家  ›  专栏  ›  技术社区  ›  John Källén

在ASP.NET中,在请求后推迟操作的最佳方法是什么。网?

  •  1
  • John Källén  · 技术社区  · 16 年前

    我正在写一个ASP。NET应用程序。当处理特定类型的请求时,我想安排在处理请求后的特定分钟内调用一个方法。延迟方法不需要与发出原始请求的客户端通信,它只是用来做一些“家务”工作。在ASP中最好的方法是什么。NET上下文?(如果应用程序域因某种原因死亡,则不触发事件是可以的)。

    3 回复  |  直到 16 年前
        1
  •  1
  •   M4N    16 年前

    在Global.asax中,使用以下命令检查您的传入请求:

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            CheckRequest(HttpContext.Current.Request);
        }
    

    如果您的请求有效,请注册缓存条目:

        private void CheckRequest(HttpRequest request)
        {
            if (request)
                RegisterCacheEntry();
        }
    
        private void RegisterCacheEntry()
        {
            if (HttpRuntime.Cache[CacheItemKey] == null)
            {
                HttpRuntime.Cache.Add(CacheItemKey, "your key", null, 
                    DateTime.Now.AddSeconds(60), //change to fire in whatever time frame you require
                    Cache.NoSlidingExpiration, 
                    CacheItemPriority.NotRemovable,
                    new CacheItemRemovedCallback(CacheItemRemovedCallback));
            }
        }
    

    然后在回调函数中处理你的函数:

        private void CacheItemRemovedCallback(string key, object value, CacheItemRemovedReason reason)
        {
            // execute your function
    
        }
    
        2
  •  1
  •   flesh    16 年前

    您可以在检查该请求是否需要计时器后,从global.asax.cs(例如application_BeginRequest)中的某个应用程序事件启动计时器(System.Timers.timer)。

    然后,在计时器的Elapsed事件的处理程序中,确保停止计时器。

    例如,将以下内容放入global.asax.cs中:

    System.Timers.Timer _timer = null;    
    void Application_BeginRequest(object sender, EventArgs e)
    {
      // check if cleanup must be initiated
      bool mustInitCleanup = RequestRequiresCleanup();
      if ((_timer == null) && mustInitCleanup)
      {
        _timer = new System.Timers.Timer(5000);
        _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);            
        _timer.Start();                     
      }     
    }
    
    void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
      _timer.Stop();
      _timer = null;        
      // do cleanup task
    }
    
        3
  •  0
  •   JB King    16 年前

    只需创建一个新线程来执行内务工作,并在开始时让它休眠,无论您希望服务器在执行操作之前等待多长时间。

    例如,在该特定请求的某个地方,您想调用DoSomething:

            aNewThread = new Thread(Foo);
            aNewThread.Start();
    

        public void Foo()
        {
            Thread.Sleep(5000);
            DoSomething();
        }
    
    推荐文章