Share via


计时器

计时器是使您能够指定要在指定时间调用的委托的轻量对象。 线程池中的线程执行等待操作。

使用 Timer 类是非常简单的。 需要创建一个 Timer,将 TimerCallback 委托传递给回调方法;还需要创建一个表示将被传递给回调的状态的对象,以及初始引发时间和表示回调调用之间的时间段的时间。 若要取消挂起的计时器,请调用 Timer.Dispose 函数。

注意注意

有两个其他计时器类。System.Windows.Forms.Timer 类是使用可视化设计器的控件,旨在用于用户界面上下文中;它对用户界面线程引发事件。System.Timers.Timer 类派生自 Component,所以它可与可视化设计器一同使用;它还引发事件,但对 ThreadPool 线程引发这些事件。System.Threading.Timer 类对 ThreadPool 线程进行回调,并且根本不使用事件模型。它还为回调方法提供状态对象,而其他计时器则不提供。它是极度轻量级的。

下面的代码示例启动一个计时器,该计时器在一秒(1000 毫秒)后启动,每秒增加一个刻度,直到按下**“Enter”**键。 包含对计时器的引用的变量是类级别字段,以确保计时器在运行期间不会被垃圾回收。 有关主动垃圾回收的更多信息,请参见 KeepAlive

Imports System
Imports System.Threading

Public Class Example
    Private Shared ticker As Timer

    Public Shared Sub TimerMethod(state As Object)
        Console.Write(".")
    End Sub

    Public Shared Sub Main()
        ticker = New Timer(AddressOf TimerMethod, Nothing, 1000, 1000)

        Console.WriteLine("Press the Enter key to end the program.")
        Console.ReadLine()
    End Sub
End Class
using System;
using System.Threading;

public class Example
{
    private static Timer ticker;

    public static void TimerMethod(object state)
    {
        Console.Write(".");
    }

    public static void Main()
    {
        ticker = new Timer(TimerMethod, null, 1000, 1000);

        Console.WriteLine("Press the Enter key to end the program.");
        Console.ReadLine();
    }
}
using namespace System;
using namespace System::Threading;

public ref class Example
{
private:
    static Timer^ ticker;

public:
    static void TimerMethod(Object^ state)
    {
        Console::Write(".");
    }

    static void Main()
    {
        TimerCallback^ tcb =
           gcnew TimerCallback(&TimerMethod);

        ticker = gcnew Timer(tcb, nullptr, 1000, 1000);

        Console::WriteLine("Press the Enter key to end the program.");
        Console::ReadLine();
    }
};

int main()
{
    Example::Main();
}

请参见

参考

Timer

其他资源

线程处理对象和功能