計時器是讓您能夠指定在指定時間呼叫之委派的輕量型物件。 執行緒集區中的執行緒會執行等候作業。
使用 Timer 類別非常簡單。 您會建立 Timer (將 TimerCallback 委派傳送至回呼方法),以及建立表示將傳給回呼之狀態的物件、初始引發時間,以及表示回呼引動過程之間的時間。 若要取消暫止計時器,請呼叫 Timer.Dispose 函式。
注意事項 |
|---|
有兩個其他計時器類別。System.Windows.Forms.Timer 類別是一個與視覺化設計工具一起使用的控制項,它是要用於使用者介面內容中;它會在使用者介面執行緒上引發事件。System.Timers.Timer 類別衍生自 Component,所以它可以與視覺化設計工具一起使用;它也會引發事件,但是在 ThreadPool 執行緒上引發。System.Threading.Timer 類別會在 ThreadPool 執行緒上進行回呼,且完全不會使用此事件模型。它也會將狀態物件提供給回呼方法,而其他計時器則不會;它是極為輕量的。 |
下列程式碼範例會啟動一個在一秒鐘 (1000 毫秒) 之後啟動的計時器,並在每一秒鐘滴答地記錄,直到按下 [Enter] 鍵為止。 包含計時器的參考之變數為類別層級的欄位,用以確保計時器仍在執行中時不受記憶體回收的控制。 如需積極型記憶體回收的詳細資訊,請參閱 KeepAlive。
Imports System
Imports System.Threading
Public Class Example
Private Shared ticker As Timer
Public Shared Sub TimerMethod(state As Object)
Console.Write(".")
End Sub
Public Shared Sub Main()
ticker = New Timer(AddressOf TimerMethod, Nothing, 1000, 1000)
Console.WriteLine("Press the Enter key to end the program.")
Console.ReadLine()
End Sub
End Class
using System;
using System.Threading;
public class Example
{
private static Timer ticker;
public static void TimerMethod(object state)
{
Console.Write(".");
}
public static void Main()
{
ticker = new Timer(TimerMethod, null, 1000, 1000);
Console.WriteLine("Press the Enter key to end the program.");
Console.ReadLine();
}
}
using namespace System;
using namespace System::Threading;
public ref class Example
{
private:
static Timer^ ticker;
public:
static void TimerMethod(Object^ state)
{
Console::Write(".");
}
static void Main()
{
TimerCallback^ tcb =
gcnew TimerCallback(&TimerMethod);
ticker = gcnew Timer(tcb, nullptr, 1000, 1000);
Console::WriteLine("Press the Enter key to end the program.");
Console::ReadLine();
}
};
int main()
{
Example::Main();
}
注意事項