Export (0) Print
Expand All

Timer Constructor (TimerCallback)

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.

Namespace:  System.Threading
Assembly:  mscorlib (in mscorlib.dll)

public Timer(
	TimerCallback callback
)

Parameters

callback
Type: System.Threading.TimerCallback
A TimerCallback delegate representing a method to be executed.

Call this constructor when you want to use the Timer object itself as the state object. After creating the timer, use the Change method to set the interval and due time.

This constructor specifies an infinite due time before the first callback and an infinite interval between callbacks, in order to prevent the first callback from occurring before the Timer object is assigned to the state object.

The method specified for callback should be reentrant, because it is called on ThreadPool threads. The method can be executed simultaneously on two thread pool threads if the timer interval is less than the time required to execute the method, or if all thread pool threads are in use and the method is queued multiple times.

The following code example creates a new timer, using the timer itself as the state object. The Change method is used to start the timer. When the timer callback occurs, the state object is used to turn the timer off.


using System;
using System.Threading;

public class Example
{
    public static void Main()
    {
        // Create an instance of the Example class, and start two
        // timers.
        Example ex = new Example();
        ex.StartTimer(2000);
        ex.StartTimer(1000);

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

    public void StartTimer(int dueTime)
    {
        Timer t = new Timer(new TimerCallback(TimerProc));
        t.Change(dueTime, 0);
    }

    private void TimerProc(object state)
    {
        // The state object is the Timer object.
        Timer t = (Timer) state;
        t.Dispose();
        Console.WriteLine("The timer callback executes.");
    }
}


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Community Additions

ADD
Show:
© 2014 Microsoft