2009-11-25 84 views
2

我有一個服務器應用程序需要安排延遲執行的方法。換句話說,就是在一段時間後使用ThreadPool中的線程運行方法的機制。使用ThreadPool安排延遲執行方法的最佳方法?

void ScheduleExecution (int delay, Action someMethod){ 
//How to implement this??? 
} 

//At some other place 

//MethodX will be executed on a thread in ThreadPool after 5 seconds 
ScheduleExecution (5000, MethodX); 

請建議一個有效的機制,以達到上述目的。我寧願避免經常創建新的對象,因爲上面的活動很可能會在服務器上發生。調用的準確性也很重要,即MethodX在5200毫秒後執行很好,但在6000毫秒後執行是個問題。

在此先感謝...

回答

4

你可以使用RegisterWaitForSingleObject方法。這裏有一個例子:

public class Program 
{ 
    static void Main() 
    { 
     var waitHandle = new AutoResetEvent(false); 
     ThreadPool.RegisterWaitForSingleObject(
      waitHandle, 
      // Method to execute 
      (state, timeout) => 
      { 
       Console.WriteLine("Hello World"); 
      }, 
      // optional state object to pass to the method 
      null, 
      // Execute the method after 2 seconds 
      TimeSpan.FromSeconds(2), 
      // Execute the method only once. You can set this to false 
      // to execute it repeatedly every 2 seconds 
      true); 
     Console.ReadLine(); 
    } 
} 
+0

我認爲這值得一提的是,任何人都希望在重複的方式(其中最後一個參數是假的),使用它會想捕捉的返回'RegisteredWaitHandle'反對這樣以後就可以調用'RegisteredWaitHandle.Unregister()'方法來防止任何進一步的執行。 – WiredWiz 2012-05-14 20:56:37