2009-01-21 78 views
1

我正在寫一個ASP.NET應用程序。在處理特定類型的請求時,我想要在處理請求後的某個數分鐘內調度一個方法。推遲的方法不需要與提出原始請求的客戶端進行通信,而只是爲了做一些「內務」工作。在ASP.NET上下文中執行此操作的最佳方法是什麼? (如果應用程序域由於某種原因死亡,則不會觸發事件)。在ASP.NET中的請求之後推遲動作的最佳方式是什麼?

回答

1

在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 

    } 
+0

我喜歡這個解決方案的最佳;這是一個給我最強大的「呃,我自己應該想到這個。」謝謝! – 2009-01-22 09:34:01

1

您可以在檢查該請求所需的情況後,從global.asax.cs中的某個應用程序事件(例如,Application_BeginRequest)中啓動一個計時器(System.Timers.Timer)。

然後,在計時器的Elapsed事件的處理程序中,確保您停止計時器。

E.g.把這樣的事情到的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 
} 
0

簡單地創建一個新的線程來完成整理工作,並且在開始時它會讓它休眠,無論長時間,您希望服務器在執行操作之前等待。

例如,在某個特定的請求要撥打的DoSomething:

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

public void Foo() 
    { 
     Thread.Sleep(5000); 
     DoSomething(); 
    } 
+0

問題是,這個解決方案將一個線程與sleep語句綁定在一起,可能不是線程使用的那個兆字節的棧。 – 2009-01-22 09:32:26

相關問題