Timer 類別
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
提供機制,以指定間隔在線程集區線程上執行方法。 此類別無法獲得繼承。
public ref class Timer sealed : IDisposable
public ref class Timer sealed : MarshalByRefObject, IDisposable
public ref class Timer sealed : MarshalByRefObject, IAsyncDisposable, IDisposable
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class Timer : IDisposable
public sealed class Timer : MarshalByRefObject, IDisposable
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class Timer : MarshalByRefObject, IDisposable
public sealed class Timer : MarshalByRefObject, IAsyncDisposable, IDisposable
[<System.Runtime.InteropServices.ComVisible(true)>]
type Timer = class
interface IDisposable
type Timer = class
inherit MarshalByRefObject
interface IDisposable
[<System.Runtime.InteropServices.ComVisible(true)>]
type Timer = class
inherit MarshalByRefObject
interface IDisposable
type Timer = class
inherit MarshalByRefObject
interface IAsyncDisposable
interface IDisposable
Public NotInheritable Class Timer
Implements IDisposable
Public NotInheritable Class Timer
Inherits MarshalByRefObject
Implements IDisposable
Public NotInheritable Class Timer
Inherits MarshalByRefObject
Implements IAsyncDisposable, IDisposable
- 繼承
-
Timer
- 繼承
- 屬性
- 實作
範例
以下範例定義了一個 StatusChecker 包含 CheckStatus 與代理相同簽名的方法 TimerCallback 的類別。
state該方法的CheckStatus參數是一個AutoResetEvent物件,用來同步應用程式執行緒與執行回調代理的執行緒池執行緒。 該 StatusChecker 類別還包含兩個狀態變數:
invokeCount
表示回調方法被呼叫的次數。
maxCount
決定回撥方法應被呼叫的最大次數。
應用程式執行緒會建立計時器,計時器會等待一秒,然後每 250 毫秒執行 CheckStatus 回調方法。 應用程式執行緒接著阻塞,直到 AutoResetEvent 物件被發出訊號。 當 CheckStatus 回調方法執行 maxCount times 時,會呼叫該 AutoResetEvent.Set 方法將物件狀態 AutoResetEvent 設為已訊號。 第一次發生時,應用程式執行緒會呼叫該 Change(Int32, Int32) 方法,使回調方法每半秒執行一次。 它再次阻擋,直到 AutoResetEvent 物體被發出信號。 當這種情況發生時,計時器會被呼叫其 Dispose 方法而被銷毀,應用程式也會終止。
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 執行的方法。 TimerCallback代表簽名如下:
void TimerCallback(Object state)
Sub TimerCallback(state As Object)
計時器代理是在計時器建構時指定,且無法更改。 該方法不會在建立計時器的執行緒上執行;它在 ThreadPool 系統提供的執行緒上執行。
Tip
.NET 包含數個計時器類別,每個類別提供不同的功能:
- System.Timers.Timer,該事件觸發事件並在一個或多個事件中執行程式碼,並定期匯入。 此類別設計用於多執行緒環境中作為伺服器端或服務元件;它沒有使用者介面,執行時也無法顯示。
- System.Threading.Timer,該方法會在執行緒池執行緒中以固定間隔執行單一回調方法。 回調方法定義於計時器實例化且無法更改時。 與類別 System.Timers.Timer 相同,此類別設計用於多執行緒環境中作為伺服器端或服務元件;它沒有使用者介面,執行時不可見。
- System.Windows.Forms.Timer,一個Windows Forms元件,會在一個或多個事件中執行程式碼,定期匯入。 該元件沒有使用者介面,設計用於單執行緒環境;它在 UI 執行緒執行。
- System.Web.UI.Timer(僅限 .NET Framework 使用),一個 ASP.NET 元件,能定期執行非同步網頁回貼。
-
System.Windows.Threading.DispatcherTimer,一個整合在
Dispatcher佇列中的計時器。 此計時器在指定時間間隔以指定優先順序進行處理。
當你建立計時器時,可以指定在方法第一次執行前等待的時間(Due Time),以及後續執行之間的等待時間(period)。 該 Timer 類別的解析度與系統時鐘相同。 這表示如果週期小於系統時鐘的解析度,TimerCallback代理會以系統時鐘解析度定義的間隔執行,該間隔在Windows 7和Windows 8系統中約為15毫秒。 你可以透過這個 Change 方法更改截止時間和時間,或停用計時器。
Note
所使用的系統時鐘與 GetTickCount 相同,且不受 timeBeginPeriod 與 timeEndPeriod 的變更影響。
當不再需要計時器時,使用 Dispose 該方法釋放計時器所持有的資源。 請注意,回調可能發生在 Dispose() 方法過載被呼叫後,因為計時器會排隊回調,讓執行緒池執行緒執行。 你可以利用 Dispose(WaitHandle) 方法過載功能,等所有回調都完成後再做。
計時器執行的回調方法應該是重載的,因為它是在執行緒中被呼叫 ThreadPool 的。 如果計時器間隔小於回調所需的時間,或所有執行緒池執行緒都在使用且回調被多次排隊,則可同時在兩個執行緒池執行緒上執行回調。
Note
System.Threading.Timer 是一個簡單且輕量的計時器,使用回調方法,並由執行緒池執行緒服務。 不建議用於 Windows Forms,因為它的回調不會發生在使用者介面執行緒中。 System.Windows.Forms.Timer 是搭配Windows Forms的較佳選擇。 對於伺服器端的計時器功能,你可以考慮使用 System.Timers.Timer,它會引發事件並具備額外功能。
建構函式
| 名稱 | Description |
|---|---|
| Timer(TimerCallback, Object, Int32, Int32) |
初始化該類別的新實例 |
| Timer(TimerCallback, Object, Int64, Int64) |
初始化該類別的新實例 |
| Timer(TimerCallback, Object, TimeSpan, TimeSpan) |
初始化類別的新實例 |
| Timer(TimerCallback, Object, UInt32, UInt32) |
初始化該類別的新實例 |
| Timer(TimerCallback) |
方法
| 名稱 | Description |
|---|---|
| Change(Int32, Int32) |
改變計時器的開始時間及方法呼叫間隔,使用 32 位元有符號整數來測量時間區間。 |
| Change(Int64, Int64) |
改變計時器的開始時間及方法呼叫間隔,使用 64 位元有號整數來衡量時間區間。 |
| Change(TimeSpan, TimeSpan) |
改變計時器的開始時間及方法呼叫間隔,並利用 TimeSpan 數值來衡量時間區間。 |
| Change(UInt32, UInt32) |
改變計時器的開始時間及方法呼叫間隔,使用 32 位元無符號整數來測量時間區間。 |
| CreateObjRef(Type) |
建立一個物件,包含產生代理伺服器所需的所有相關資訊,用於與遠端物件通訊。 (繼承來源 MarshalByRefObject) |
| Dispose() |
釋放目前實例 Timer所使用的所有資源。 |
| Dispose(WaitHandle) |
釋放目前實例 Timer 所使用的所有資源,並在計時器被處理完時發出信號。 |
| DisposeAsync() |
釋放目前實例 Timer所使用的所有資源。 |
| Equals(Object) |
判斷指定的 物件是否等於目前的物件。 (繼承來源 Object) |
| Finalize() |
允許對象嘗試釋放資源,並在垃圾收集回收之前執行其他清除作業。 |
| GetHashCode() |
做為預設雜湊函式。 (繼承來源 Object) |
| GetLifetimeService() |
取得目前控制此實例生命週期政策的終身服務物件。 (繼承來源 MarshalByRefObject) |
| GetType() |
取得目前實例的 Type。 (繼承來源 Object) |
| InitializeLifetimeService() |
取得一個終身服務物件以控制此實例的終身政策。 (繼承來源 MarshalByRefObject) |
| MemberwiseClone() |
建立目前 Object的淺層複本。 (繼承來源 Object) |
| MemberwiseClone(Boolean) |
建立一個 MarshalByRefObject 目前物件的淺層複製品。 (繼承來源 MarshalByRefObject) |
| ToString() |
傳回表示目前 物件的字串。 (繼承來源 Object) |
擴充方法
| 名稱 | Description |
|---|---|
| ConfigureAwait(IAsyncDisposable, Boolean) |
設定如何執行從異步可處置專案傳回的工作等候。 |
適用於
執行緒安全性
此類型是安全線程。