我被告知,與使用Thread.Sleep(int)
使程序在繼續之前等待一段時間相反,我應該使用定時器。如何在C#中使用計時器在做某些事情之前等待一段時間?
我想知道這應該怎麼做?有人能給我一個簡短的例子嗎?
我被告知,與使用Thread.Sleep(int)
使程序在繼續之前等待一段時間相反,我應該使用定時器。如何在C#中使用計時器在做某些事情之前等待一段時間?
我想知道這應該怎麼做?有人能給我一個簡短的例子嗎?
myTimer.Tick += new EventHandler(TimerEventProcessor);
// Sets the timer interval to 5 seconds.
myTimer.Interval = 5000;
myTimer.Start();
這將導致TimeEventProcessor在5秒內執行而不會阻塞當前線程。
創建
Timer _timer = new Timer();
定時器初始化
_timer.Interval = 5000; // Time in milliseconds.
_timer.Tick += Timer_Tick;
_timer.Start();
計時器的計時器滴答事件處理
void Timer_Tick(object sender, EventArgs e)
{
// Do the timed work here
}
您可以
_timer.Stop();
0123停止計時器
UPDATE
可以將System.Windows.Forms.Timer
-component到Form
添加(到其元件托盤是精確的)。這具有可以從屬性窗口設置其屬性和Tick-event的優點。
還請查看其他計時器的文檔:System.Threading.Timer,System.Timers.Timer,System.Web.UI.Timer和System.Windows.Threading.DispatcherTimer。阿布舍克蘇爾寫了一個不錯的比較here
你有什麼試過?你看看msdn上的第一個命中嗎? http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx – BrokenGlass 2012-02-12 19:27:28