作用:每隔多久去執行線程里的方法.
class ThreadTimerDemo { static void Main(string[] args) { // Create an AutoResetEvent to signal the timeout threshold in the // timer callback has been reached. var autoEvent = new AutoResetEvent(false); var statusChecker = new StatusChecker(10); // Create a timer that invokes CheckStatus after one second, // and every 1/4 second thereafter. Console.WriteLine("{0:h:mm:ss.fff} Creating timer.\n", DateTime.Now); var stateTimer = new Timer(statusChecker.CheckStatus, autoEvent, 1000, 250); // When autoEvent signals, change the period to every half second. autoEvent.WaitOne(); stateTimer.Change(0, 500); Console.WriteLine("\nChanging period to .5 seconds.\n"); // When autoEvent signals the second time, dispose of the timer. autoEvent.WaitOne(); stateTimer.Change(0, 1000); Console.WriteLine("\nChanging period to 1 seconds.\n"); autoEvent.WaitOne(); stateTimer.Dispose(); Console.WriteLine("\nDestroying timer."); Console.ReadKey(); } class StatusChecker { private int invokeCount; private int maxCount; public StatusChecker(int count) { invokeCount = 0; maxCount = count; } // This method is called by the timer delegate. public void CheckStatus(Object stateInfo) { AutoResetEvent autoEvent = (AutoResetEvent)stateInfo; Console.WriteLine("{0} Checking status {1,2}.", DateTime.Now.ToString("h:mm:ss.fff"), (++invokeCount).ToString()); if (invokeCount == maxCount) { // Reset the counter and signal the waiting thread. invokeCount = 0; autoEvent.Set(); } } } }
// The example displays output like the following: // 11:59:54.202 Creating timer. // // 11:59:55.217 Checking status 1. // 11:59:55.466 Checking status 2. // 11:59:55.716 Checking status 3. // 11:59:55.968 Checking status 4. // 11:59:56.218 Checking status 5. // 11:59:56.470 Checking status 6. // 11:59:56.722 Checking status 7. // 11:59:56.972 Checking status 8. // 11:59:57.223 Checking status 9. // 11:59:57.473 Checking status 10. // // Changing period to .5 seconds. // // 11:59:57.474 Checking status 1. // 11:59:57.976 Checking status 2. // 11:59:58.476 Checking status 3. // 11:59:58.977 Checking status 4. // 11:59:59.477 Checking status 5. // 11:59:59.977 Checking status 6. // 12:00:00.478 Checking status 7. // 12:00:00.980 Checking status 8. // 12:00:01.481 Checking status 9. // 12:00:01.981 Checking status 10. // // Destroying timer.
.NET 包括四個類名為Timer
,每個的它提供了不同的功能:
- System.Timers.Timer它觸發事件並執行的代碼中一個或多個事件接收器按固定間隔。 類適用於作為基於服務器的使用或在多線程環境; 中的服務組件它沒有用戶界面並不是在運行時中可見。
- System.Threading.Timer其中按固定間隔在線程池線程上執行的單個回調方法。 當計時器實例化,並且不能更改定義的回調方法。 如System.Timers.Timer類,此類旨在為基於服務器或服務組件在多線程環境中使用; 它沒有用戶界面並不是在運行時中可見。
- System.Windows.Forms.Timer (僅在.NET framework 中),觸發事件並在固定時間間隔的一個或多個事件接收器中執行代碼的 Windows 窗體組件。 該組件沒有用戶界面,專供在單線程環境中;它在 UI 線程上執行。
- System.Web.UI.Timer (僅在.NET framework 中),按固定時間間隔執行異步或同步網頁回發的 ASP.NET 組件。