分类:
2008-10-13 16:09:08
System.Timers.Timer tmrTimersTimer = new System.Timers.Timer(); tmrTimersTimer.Interval = 1000; tmrTimersTimer.Elapsed += new ElapsedEventHandler(tmrTimersTimers_Elapsed); tmrTimersTimer.SynchronizingObject = this; //Synchronize with //the current form... trmTimersTimer.Start(); ... private void tmrTimersTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { // Do something on the UI thread (same thread the form was // created on)... // If we didnt set SynchronizingObject we would be on a // worker thread... }
System.Timers.Timer Started @ 5:15:01 PM --> Timer Event 1 @ 5:15:02 PM on Thread: WorkerThread --> Timer Event 2 @ 5:15:03 PM on Thread: WorkerThread --> Timer Event 3 @ 5:15:04 PM on Thread: WorkerThread Sleeping for 5000 ms... --> Timer Event 4 @ 5:15:05 PM on Thread: WorkerThread --> Timer Event 5 @ 5:15:06 PM on Thread: WorkerThread --> Timer Event 6 @ 5:15:07 PM on Thread: WorkerThread --> Timer Event 7 @ 5:15:08 PM on Thread: WorkerThread --> Timer Event 8 @ 5:15:09 PM on Thread: WorkerThread System.Timers.Timer Stopped @ 5:15:10 PM
System.Threading.Timer Started @ 7:17:11 AM --> Timer Event 1 @ 7:17:12 AM on Thread: WorkerThread --> Timer Event 2 @ 7:17:13 AM on Thread: WorkerThread --> Timer Event 3 @ 7:17:14 AM on Thread: WorkerThread Sleeping for 5000 ms... --> Timer Event 4 @ 7:17:15 AM on Thread: WorkerThread --> Timer Event 5 @ 7:17:16 AM on Thread: WorkerThread --> Timer Event 6 @ 7:17:17 AM on Thread: WorkerThread --> Timer Event 7 @ 7:17:18 AM on Thread: WorkerThread --> Timer Event 8 @ 7:17:19 AM on Thread: WorkerThread System.Threading.Timer Stopped @ 7:17:20 AM
private void ShowTimerEventFired(DateTime eventTime, string threadName) { //InvokeRequired will be true when using //System.Threading.Timer or System.Timers.Timer (without a //SynchronizationObject)... if (lstTimerEvents.InvokeRequired) { //Marshal this call back to the UI thread (via the form //instance)... BeginInvoke(new ShowTimerEventFiredDelegate(ShowTimerEventFired), new object[] {eventTime, threadName}); } else lstTimerEvents.TopIndex = lstTimerEvents.Items.Add( String.Format("—> Timer Event {0} @ {1} on Thread: {2}", ++_tickEventCounter, eventTime.ToLongTimeString(), threadName)); }
           | System.Windows.Forms | System.Timers | System.Threading |
---|---|---|---|
定时事件运行在什么线程? | UI 线程 | UI 或工作者线程 | 工作者线程 |
实例是否线程安全? | 否 | 是 | 否 |
有类似/直觉 对象模型么? | 是 | 是 | 否 |
要求Windows窗体么? | 是 | 否 | 否 |
节拍质量跳动? | 否 | 是* | 是* |
定时事件支持 state 对象么? | 否 | 否 | 是 |
初始定时事件可以被规划么? | 否 | 否 | 是 |
类支持继承么? | 是 | 是 | 否 |
* 依赖于是否可以得到系统资源 (如工作者线程) |