Timer Timer Timer Timer Class

定義

提供一套機制,可於指定間隔在執行緒集區執行緒上執行方法。Provides a mechanism for executing a method on a thread pool thread at specified intervals. 這個類別無法被繼承。This class cannot be inherited.

public ref class Timer sealed : MarshalByRefObject, IDisposable
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class Timer : MarshalByRefObject, IDisposable
type Timer = class
    inherit MarshalByRefObject
    interface IDisposable
Public NotInheritable Class Timer
Inherits MarshalByRefObject
Implements IDisposable
繼承
屬性
實作

範例

下列範例會定義StatusChecker類別,其中包含CheckStatus其簽章是相同的方法為TimerCallback委派。The following example defines a StatusChecker class that includes a CheckStatus method whose signature is the same as the TimerCallback delegate. state引數CheckStatus方法是AutoResetEvent物件,用來同步處理應用程式執行緒和執行緒集區執行緒執行回呼委派。The state argument of the CheckStatus method is an AutoResetEvent object that is used to synchronize the application thread and the thread pool thread that executes the callback delegate. StatusChecker類別也包含兩個狀態變數:The StatusChecker class also includes two state variables:

invokeCount
表示叫用回呼方法的次數。Indicates the number of times the callback method has been invoked.

maxCount
決定應叫用回呼方法最大次數。Determines the maximum number of times the callback method should be invoked.

應用程式執行緒會建立計時器,它會等待一秒,然後執行CheckStatus回呼方法每 250 毫秒。The application thread creates the timer, which waits one second and then executes the CheckStatus callback method every 250 milliseconds. 然後,應用程式執行緒會封鎖直到AutoResetEvent物件收到訊號。The application thread then blocks until the AutoResetEvent object is signaled. CheckStatus回呼方法會執行maxCount次,它會呼叫AutoResetEvent.Set方法,以設定狀態的AutoResetEvent物件已收到訊號。When the CheckStatus callback method executes maxCount times, it calls the AutoResetEvent.Set method to set the state of the AutoResetEvent object to signaled. 第一次發生這種情況,應用程式執行緒呼叫Change(Int32, Int32)方法以便在回呼方法現在會執行每個半秒。The first time this happens, the application thread calls the Change(Int32, Int32) method so that the callback method now executes every half second. 同樣地封鎖直到AutoResetEvent物件收到訊號。It once again blocks until the AutoResetEvent object is signaled. 當發生這種情況時,計時器會終結藉由呼叫其Dispose方法,以及應用程式會終止。When this happens, the timer is destroyed by calling its Dispose method, and the application terminates.

using namespace System;
using namespace System::Threading;

ref class StatusChecker
{
private:
    int invokeCount, maxCount;

public:
    StatusChecker(int count)
    {
        invokeCount  = 0;
        maxCount = count;
    }

    // This method is called by the timer delegate.
    void CheckStatus(Object^ stateInfo)
    {
        AutoResetEvent^ autoEvent = dynamic_cast<AutoResetEvent^>(stateInfo);
        Console::WriteLine("{0:h:mm:ss.fff} Checking status {1,2}.",
                           DateTime::Now, ++invokeCount);

        if (invokeCount == maxCount) {
            // Reset the counter and signal the waiting thread.
            invokeCount  = 0;
            autoEvent->Set();
        }
    }
};

ref class TimerExample
{
public:
    static void Main()
    {
        // Create an AutoResetEvent to signal the timeout threshold in the
        // timer callback has been reached.
        AutoResetEvent^ autoEvent = gcnew AutoResetEvent(false);

        StatusChecker^ statusChecker = gcnew StatusChecker(10);

        // Create a delegate that invokes methods for the timer.
        TimerCallback^ tcb =
           gcnew TimerCallback(statusChecker, &StatusChecker::CheckStatus);

        // 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);
        Timer^ stateTimer = gcnew Timer(tcb, autoEvent, 1000, 250);

        // When autoEvent signals, change the period to every half second.
        autoEvent->WaitOne(5000, false);
        stateTimer->Change(0, 500);
        Console::WriteLine("\nChanging period to .5 seconds.\n");

        // When autoEvent signals the second time, dispose of the timer.
        autoEvent->WaitOne(5000, false);
        stateTimer->~Timer();
        Console::WriteLine("\nDestroying timer.");
    }
};

int main()
{
    TimerExample::Main();
}
// 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.
using System;
using System.Threading;

class TimerExample
{
    static void Main()
    {
        // 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.Dispose();
        Console.WriteLine("\nDestroying timer.");
    }
}

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.
Imports System.Threading

Public Module Example
    Public Sub Main()
        ' Use an AutoResetEvent to signal the timeout threshold in the
        ' timer callback has been reached.
        Dim autoEvent As New AutoResetEvent(False)

        Dim statusChecker As 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." & vbCrLf, 
                          DateTime.Now)
        Dim stateTimer As New Timer(AddressOf statusChecker.CheckStatus, 
                                    autoEvent, 1000, 250)

        ' When autoEvent signals, change the period to every half second.
        autoEvent.WaitOne()
        stateTimer.Change(0, 500)
        Console.WriteLine(vbCrLf & "Changing period to .5 seconds." & vbCrLf)

        ' When autoEvent signals the second time, dispose of the timer.
        autoEvent.WaitOne()
        stateTimer.Dispose()
        Console.WriteLine(vbCrLf & "Destroying timer.")
    End Sub
End Module

Public Class StatusChecker
    Dim invokeCount, maxCount As Integer 

    Sub New(count As Integer)
        invokeCount  = 0
        maxCount = count
    End Sub

    ' The timer callback method.
    Sub CheckStatus(stateInfo As Object)
        Dim autoEvent As AutoResetEvent = DirectCast(stateInfo, AutoResetEvent)
        invokeCount += 1
        Console.WriteLine("{0:h:mm:ss.fff} Checking status {1,2}.", 
                          DateTime.Now, invokeCount)
        If invokeCount = maxCount Then
            ' Reset the counter and signal the waiting thread.
            invokeCount = 0
            autoEvent.Set()
        End If
    End Sub
End Class
' 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.

備註

使用TimerCallback來指定您想要的方法委派Timer來執行。Use a TimerCallback delegate to specify the method you want the Timer to execute. 簽章TimerCallback委派:The signature of the TimerCallback delegate is:

void TimerCallback(Object state)  
void TimerCallback(Object state)  
Sub TimerCallback(state As Object)  

當計時器建構,而且無法變更,會指定計時器委派。The timer delegate is specified when the timer is constructed, and cannot be changed. 此方法不會建立計時器; 在執行緒上執行它會執行上ThreadPool系統所提供的執行緒。The method does not execute on the thread that created the timer; it executes on a ThreadPool thread supplied by the system.

提示

.NET 包含四個類別,名為Timer,每個的提供不同的功能:.NET includes four classes named Timer, each of which offers different functionality:

  • System.Timers.Timer這會引發事件,並在其中執行程式碼或定期的更多的事件接收。System.Timers.Timer, which fires an event and executes the code in one or more event sinks at regular intervals. 此類別被為了做為以伺服器為基礎,或在多執行緒環境; 中的服務元件它沒有使用者介面,並在執行階段看不到。The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Threading.Timer它就會在固定間隔在執行緒集區執行緒上執行的單一回呼方法。System.Threading.Timer, which executes a single callback method on a thread pool thread at regular intervals. 計時器會具現化,而且無法加以變更,被定義回呼方法。The callback method is defined when the timer is instantiated and cannot be changed. 例如System.Timers.Timer類別,這個類別是做為伺服器或服務的元件,在多執行緒環境中用於; 它沒有使用者介面,並在執行階段看不到。Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Windows.Forms.Timer (僅限.NET framework),Windows Forms 元件引發事件,並在一或多個事件接收器,定期執行程式碼。System.Windows.Forms.Timer (.NET Framework only), a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. 元件沒有使用者介面,而且是用於單一執行緒的環境;它會在 UI 執行緒上執行。The component has no user interface and is designed for use in a single-threaded environment; it executes on the UI thread.
  • System.Web.UI.Timer (僅限.NET framework),以固定間隔執行非同步或同步網頁回傳的 ASP.NET 元件。System.Web.UI.Timer (.NET Framework only), an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.

當您建立計時器時,您可以指定的方法第一次執行之前要等待的時間量 (到期時間),以及後續的執行作業 (句點) 之間要等候的時間量。When you create a timer, you can specify an amount of time to wait before the first execution of the method (due time), and an amount of time to wait between subsequent executions (period). Timer類別具有相同的解析度,以系統時鐘。The Timer class has the same resolution as the system clock. 這表示,如果長度小於系統時鐘的解析度TimerCallback委派將在大約 15 毫秒在 Windows 7 和 Windows 8 的系統系統時鐘的解析度所定義的時間間隔執行。This means that if the period is less than the resolution of the system clock, the TimerCallback delegate will execute at intervals defined by the resolution of the system clock, which is approximately 15 milliseconds on Windows 7 and Windows 8 systems. 您可以變更到期時間和期間或停用計時器,使用Change方法。You can change the due time and period, or disable the timer, by using the Change method.

注意

只要您使用Timer,您必須保持它的參考。As long as you are using a Timer, you must keep a reference to it. 如同任何受管理的物件,Timer時不有任何參考受限於記憶體回收。As with any managed object, a Timer is subject to garbage collection when there are no references to it. 事實上,Timer時仍作用中不會防止它所收集。The fact that a Timer is still active does not prevent it from being collected.

若不再需要計時器,使用Dispose計時器所持有的方法來釋放資源。When a timer is no longer needed, use the Dispose method to free the resources held by the timer. 請注意回呼可能會發生之後Dispose()方法多載呼叫,因為計時器佇列中由執行緒集區執行緒執行的回呼。Note that callbacks can occur after the Dispose() method overload has been called, because the timer queues callbacks for execution by thread pool threads. 您可以使用Dispose(WaitHandle)等候,直到所有的回呼已完成的方法多載。You can use the Dispose(WaitHandle) method overload to wait until all callbacks have completed.

計時器所執行的回呼方法應該是可重新進入,因為已呼叫方法ThreadPool執行緒。The callback method executed by the timer should be reentrant, because it is called on ThreadPool threads. 如果計時器間隔小於執行回呼中,所需的時間,或如果所有的執行緒集區正在使用中,回呼會排入佇列多次,則可以在兩個執行緒集區執行緒上同時執行的回呼。The callback can be executed simultaneously on two thread pool threads if the timer interval is less than the time required to execute the callback, or if all thread pool threads are in use and the callback is queued multiple times.

注意

System.Threading.Timer 是簡單、 輕量的計時器,會使用回呼方法,並由執行緒集區。System.Threading.Timer is a simple, lightweight timer that uses callback methods and is served by thread pool threads. 不建議用於 Windows Form,因為其回呼不會發生在使用者介面執行緒上。It is not recommended for use with Windows Forms, because its callbacks do not occur on the user interface thread. System.Windows.Forms.Timer 是較好的選擇,以搭配 Windows Form。System.Windows.Forms.Timer is a better choice for use with Windows Forms. 如需伺服器為基礎的計時器功能,您可以考慮使用System.Timers.Timer,這會引發事件,並提供額外的功能。For server-based timer functionality, you might consider using System.Timers.Timer, which raises events and has additional features.

建構函式

Timer(TimerCallback) Timer(TimerCallback) Timer(TimerCallback) Timer(TimerCallback)

初始化的新執行個體Timer類別以無限週期和無限到期時,使用新建立Timer物件做為狀態物件。Initializes a new instance of the Timer class with an infinite period and an infinite due time, using the newly created Timer object as the state object.

Timer(TimerCallback, Object, Int32, Int32) Timer(TimerCallback, Object, Int32, Int32) Timer(TimerCallback, Object, Int32, Int32) Timer(TimerCallback, Object, Int32, Int32)

初始化的新執行個體Timer類別,使用 32 位元帶正負號的整數來指定時間間隔。Initializes a new instance of the Timer class, using a 32-bit signed integer to specify the time interval.

Timer(TimerCallback, Object, Int64, Int64) Timer(TimerCallback, Object, Int64, Int64) Timer(TimerCallback, Object, Int64, Int64) Timer(TimerCallback, Object, Int64, Int64)

初始化的新執行個體Timer類別,使用 64 位元帶正負號的整數來測量時間間隔。Initializes a new instance of the Timer class, using 64-bit signed integers to measure time intervals.

Timer(TimerCallback, Object, TimeSpan, TimeSpan) Timer(TimerCallback, Object, TimeSpan, TimeSpan) Timer(TimerCallback, Object, TimeSpan, TimeSpan) Timer(TimerCallback, Object, TimeSpan, TimeSpan)

初始化的新執行個體Timer類別,使用TimeSpan來測量時間間隔的值。Initializes a new instance of the Timer class, using TimeSpan values to measure time intervals.

Timer(TimerCallback, Object, UInt32, UInt32) Timer(TimerCallback, Object, UInt32, UInt32) Timer(TimerCallback, Object, UInt32, UInt32) Timer(TimerCallback, Object, UInt32, UInt32)

初始化的新執行個體Timer類別,使用 32 位元不帶正負號的整數來測量時間間隔。Initializes a new instance of the Timer class, using 32-bit unsigned integers to measure time intervals.

方法

Change(Int32, Int32) Change(Int32, Int32) Change(Int32, Int32) Change(Int32, Int32)

變更開始的時間和計時器的方法引動過程之間的時間間隔,使用 32 位元帶正負號的整數來測量時間間隔。Changes the start time and the interval between method invocations for a timer, using 32-bit signed integers to measure time intervals.

Change(Int64, Int64) Change(Int64, Int64) Change(Int64, Int64) Change(Int64, Int64)

變更開始的時間和計時器的方法引動過程之間的時間間隔,使用 64 位元帶正負號的整數來測量時間間隔。Changes the start time and the interval between method invocations for a timer, using 64-bit signed integers to measure time intervals.

Change(TimeSpan, TimeSpan) Change(TimeSpan, TimeSpan) Change(TimeSpan, TimeSpan) Change(TimeSpan, TimeSpan)

變更開始時間和計時器,使用的方法引動過程之間的間隔TimeSpan來測量時間間隔的值。Changes the start time and the interval between method invocations for a timer, using TimeSpan values to measure time intervals.

Change(UInt32, UInt32) Change(UInt32, UInt32) Change(UInt32, UInt32) Change(UInt32, UInt32)

變更開始的時間和計時器的方法引動過程之間的時間間隔,使用 32 位元不帶正負號的整數來測量時間間隔。Changes the start time and the interval between method invocations for a timer, using 32-bit unsigned integers to measure time intervals.

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Dispose() Dispose() Dispose() Dispose()

目前的執行個體所使用的資源全部釋出TimerReleases all resources used by the current instance of Timer.

Dispose(WaitHandle) Dispose(WaitHandle) Dispose(WaitHandle) Dispose(WaitHandle)

目前的執行個體所使用的資源全部釋出Timer和計時器已被處置時發出訊號。Releases all resources used by the current instance of Timer and signals when the timer has been disposed of.

DisposeAsync() DisposeAsync() DisposeAsync() DisposeAsync()
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
Finalize() Finalize() Finalize() Finalize()

在記憶體回收開始前,允許物件嘗試釋放資源,並執行其他清除作業。Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

取得存留期服務物件,以控制這個執行個體的存留期原則。Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
ToString() ToString() ToString() ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)

適用於

執行緒安全性

此型別具備執行緒安全。This type is thread safe.

另請參閱