三、線程計時器(System.Threading.Timer)
線程計時器也不依賴表單,是一種簡單的、羽量級計時器,它使用回調方法而不是使用事件,並由線程池線程提供支援。
對消息不線上程上發送的方案中,線程計時器是非常有用的。
使用方法如下:
System.Threading.Timer threadTimer;
public void ThreadMethod(Object state)
{
//使用代理
string text = "子線程執行,線程ID:" + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + "\r\n";
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
i++;
}
private void Form1_Load(object sender, EventArgs e)
{
threadTimer = new System.Threading.Timer(new System.Threading.TimerCallback(ThreadMethod), null, -1, -1);
}
暫停代碼:
threadTimer.Change(-1, -1);
實驗的效果和基於伺服器的計時器(System.Timers.Timer)的第二種方式是一樣的,
當然具體的使用方法和原理是不一樣的,最主要的就是這種方式使用的是代理的方式而不是事件的方式,並且可以不依賴於表單和元件而單獨執行
下面列出老外總結的一張表(三種方式的區別):
Feature description
System.Timers.Timer
System.Threading.Timer
System.Windows.Forms.Timer
Support for adding and removing listeners after the timer is instantiated.
Yes
No
Yes
Supports call backs on the user-interface thread
Yes
No
Yes
Calls back from threads obtained from the thread pool
Yes
Yes
No
Supports drag-and-drop in the Windows Forms Designer
Yes
No
Yes
Suitable for running in a server multi-threaded environment
Yes
Yes
No
Includes support for passing arbitrary state from the timer initialization to the callback.
No
Yes
No
Implements IDisposable
Yes
Yes
Yes
Supports one-off callbacks as well as periodic repeating callbacks
Yes
Yes
Yes
Accessible across application domain boundaries
Yes
Yes
Yes
Supports IComponent – hostable in an IContainer
Yes
No
Yes