Timers

Timers are lightweight objects that enable you to specify a delegate to be called at a specified time. A thread in the thread pool performs the wait operation.

Using the Timer class is straightforward. You create a Timer, passing a TimerCallback delegate to the callback method, an object representing state that will be passed to the callback, an initial raise time, and a time representing the period between callback invocations. To cancel a pending timer, call the Timer.Dispose function.

Note

There are two other timer classes. The System.Windows.Forms.Timer class is a control that works with visual designers and is meant to be used in user interface contexts; it raises events on the user interface thread. The System.Timers.Timer class derives from Component, so it can be used with visual designers; it also raises events, but it raises them on a ThreadPool thread. The System.Threading.Timer class makes callbacks on a ThreadPool thread and does not use the event model at all. It also provides a state object to the callback method, which the other timers do not. It is extremely lightweight.

The following code example starts a timer that starts after one second (1000 milliseconds) and ticks every second until you press the Enter key. The variable containing the reference to the timer is a class-level field, to ensure that the timer is not subject to garbage collection while it is still running. For more information on aggressive garbage collection, see 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();
}

See Also

Reference

Timer

Other Resources

Threading Objects and Features