Timer 類別

定義

提供一套機制,可於指定間隔在執行緒集區執行緒上執行方法。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. CheckStatus方法state的引數是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. 當回呼方法執行maxCount AutoResetEvent時間時, 它會呼叫方法,將物件的狀態設定為已發出信號。AutoResetEvent.Set CheckStatusWhen 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.

備註

使用委派來指定您Timer想要執行的方法。 TimerCallbackUse 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委派會以系統時鐘解析所定義的間隔來執行, 這大約是 windows 7 和 windows 8 系統上的15毫秒。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. 如同任何 managed 物件, 當沒有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 Forms 使用, 因為它的回呼不會發生在使用者介面執行緒上。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 Forms 搭配使用的較佳選擇。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 類別的新執行個體,利用新建立 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 類別的新執行個體,使用 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 類別的新執行個體,使用 64 位元帶正負號的整數來測量時間間隔。Initializes a new instance of the Timer class, using 64-bit signed integers to measure time intervals.

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 類別的新執行個體,使用 32 位元不帶正負號的整數 (Unsigned Integer) 來測量時間間隔。Initializes a new instance of the Timer class, using 32-bit unsigned integers to measure time intervals.

屬性

ActiveCount

取得目前有效的計時器數。Gets the number of timers that are currently active. 有註冊的有效計時器會在未來某個時間發出滴答聲,且尚未受到取消。An active timer is registered to tick at some point in the future, and has not yet been canceled.

方法

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)

變更開始的時間和計時器的方法引動過程之間的時間間隔,使用 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)

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

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)

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

(繼承來源 MarshalByRefObject)
Dispose()

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

Dispose(WaitHandle)

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

DisposeAsync()

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

Equals(Object)

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

(繼承來源 Object)
Finalize()

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

GetHashCode()

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

(繼承來源 Object)
GetLifetimeService()

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

(繼承來源 MarshalByRefObject)
GetType()

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

(繼承來源 Object)
InitializeLifetimeService()

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

(繼承來源 MarshalByRefObject)
MemberwiseClone()

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

(繼承來源 Object)
MemberwiseClone(Boolean)

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

(繼承來源 MarshalByRefObject)
ToString()

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

(繼承來源 Object)

適用於

執行緒安全性

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

另請參閱