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
public sealed class Timer : IDisposable
public sealed class Timer : 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
type Timer = class
    interface IDisposable
type Timer = class
    inherit MarshalByRefObject
    interface IAsyncDisposable
    interface 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
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方法的参数 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 委托来指定要执行的方法 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 包含多个 timer 类,每个类都提供不同的功能:.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 窗体组件。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.

创建计时器时,可以指定在第一次执行方法之前要等待的时间量 (截止时间) ,并在后续执行 (period) 之间等待一段时间。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. 与任何托管对象一样,当没有对 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.

由计时器执行的回调方法应可重入,因为它是在线程上调用的 ThreadPoolThe 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 窗体一起使用,因为它的回调不会在用户界面线程上发生。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 窗体一起使用的更好选择。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)

使用 32 位的有符号整数指定时间间隔,初始化 Timer 类的新实例。Initializes a new instance of the Timer class, using a 32-bit signed integer to specify the time interval.

Timer(TimerCallback, Object, Int64, Int64)

用 64 位有符号整数来度量时间间隔,以初始化 Timer 类的新实例。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)

用 32 位无符号整数来度量时间间隔,以初始化 Timer 类的新实例。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)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。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()

检索控制此实例的生存期策略的当前生存期服务对象。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)

配置如何执行从异步可处置项返回的任务的等待。Configures how awaits on the tasks returned from an async disposable are performed.

适用于

线程安全性

此类型是线程安全的。This type is thread safe.

另请参阅