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 : IDisposable
public ref class Timer sealed : MarshalByRefObject, IAsyncDisposable, IDisposable
public ref class Timer sealed : MarshalByRefObject, IDisposable
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class Timer : IDisposable
public sealed class Timer : MarshalByRefObject, IAsyncDisposable, IDisposable
public sealed class Timer : MarshalByRefObject, IDisposable
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class Timer : MarshalByRefObject, IDisposable
[<System.Runtime.InteropServices.ComVisible(true)>]
type Timer = class
    interface IDisposable
type Timer = class
    inherit MarshalByRefObject
    interface IAsyncDisposable
    interface IDisposable
type Timer = class
    inherit MarshalByRefObject
    interface IDisposable
[<System.Runtime.InteropServices.ComVisible(true)>]
type Timer = class
    inherit MarshalByRefObject
    interface IDisposable
Public NotInheritable Class Timer
Implements IDisposable
Public NotInheritable Class Timer
Inherits MarshalByRefObject
Implements IAsyncDisposable, IDisposable
Public NotInheritable Class Timer
Inherits MarshalByRefObject
Implements IDisposable
繼承
Timer
繼承
屬性
實作

範例

下列範例定義的 StatusChecker 類別包含其簽章與 CheckStatus 委派相同的方法 TimerCallbackThe following example defines a StatusChecker class that includes a CheckStatus method whose signature is the same as the TimerCallback delegate. state方法的引數 CheckStatusAutoResetEvent 用來同步處理應用程式執行緒和執行緒集區執行緒的物件,該執行緒會執行回呼委派。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.

應用程式執行緒會建立計時器,它會等候1秒,然後 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 委派來指定您要執行的方法 TimerUse 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 包含數個計時器類別,每個類別都提供不同的功能:.NET includes several timer classes, 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.
  • System.Windows.Threading.DispatcherTimer,這是已整合到佇列中的計時器 DispatcherSystem.Windows.Threading.DispatcherTimer, a timer that's integrated into the Dispatcher queue. 此計時器會在指定的時間間隔內以指定的優先順序進行處理。This timer is processed with a specified priority at a specified time 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. 您可以使用方法來變更到期時間和期間,或停用計時器 ChangeYou 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 的淺層複製。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)

擴充方法

ConfigureAwait(IAsyncDisposable, Boolean)

設定如何執行從非同步可處置項目傳回的工作 await。Configures how awaits on the tasks returned from an async disposable are performed.

適用於

執行緒安全性

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

另請參閱