Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

Timer Class

Provides a mechanism for executing a method at specified intervals. This class cannot be inherited.

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

[ComVisibleAttribute(true)]
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
	ExternalThreading = true)]
public sealed class Timer : MarshalByRefObject, 
	IDisposable

The Timer type exposes the following members.

  NameDescription
Public methodTimer(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.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryTimer(TimerCallback, Object, Int32, Int32)Initializes a new instance of the Timer class, using a 32-bit signed integer to specify the time interval.
Public methodSupported by the XNA FrameworkTimer(TimerCallback, Object, Int64, Int64)Initializes a new instance of the Timer class, using 64-bit signed integers to measure time intervals.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryTimer(TimerCallback, Object, TimeSpan, TimeSpan)Initializes a new instance of the Timer class, using TimeSpan values to measure time intervals.
Public methodSupported by the XNA FrameworkTimer(TimerCallback, Object, UInt32, UInt32)Initializes a new instance of the Timer class, using 32-bit unsigned integers to measure time intervals.
Top

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryChange(Int32, Int32)Changes the start time and the interval between method invocations for a timer, using 32-bit signed integers to measure time intervals.
Public methodSupported by the XNA FrameworkChange(Int64, Int64)Changes the start time and the interval between method invocations for a timer, using 64-bit signed integers to measure time intervals.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryChange(TimeSpan, TimeSpan)Changes the start time and the interval between method invocations for a timer, using TimeSpan values to measure time intervals.
Public methodSupported by the XNA FrameworkChange(UInt32, UInt32)Changes the start time and the interval between method invocations for a timer, using 32-bit unsigned integers to measure time intervals.
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryDispose()Releases all resources used by the current instance of Timer.
Public methodDispose(WaitHandle)Releases all resources used by the current instance of Timer and signals when the timer has been disposed of.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibraryFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibraryMemberwiseClone()Creates a shallow copy of the current Object. (Inherited from Object.)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryToStringReturns a string that represents the current object. (Inherited from Object.)
Top

Use a TimerCallback delegate to specify the method you want the Timer to execute. The timer delegate is specified when the timer is constructed, and cannot be changed. The method does not execute on the thread that created the timer; it executes on a ThreadPool thread supplied by the system.

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). You can change these values, or disable the timer, using the Change method.

NoteNote

As long as you are using a Timer, you must keep a reference to it. As with any managed object, a Timer is subject to garbage collection when there are no references to it. The fact that a Timer is still active does not prevent it from being collected.

When a timer is no longer needed, use the Dispose method to free the resources held by the timer. Note that callbacks can occur after the Dispose() method overload has been called, because the timer queues callbacks for execution by thread pool threads. You can use the Dispose(WaitHandle) method overload to wait until all callbacks have completed.

The 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.

NoteNote

System.Threading.Timer is a simple, lightweight timer that uses callback methods and is served by thread pool threads. It is not recommended for use with Windows Forms, because its callbacks do not occur on the user interface thread. System.Windows.Forms.Timer is a better choice for use with Windows Forms. For server-based timer functionality, you might consider using System.Timers.Timer, which raises events and has additional features.

NoteNote

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: Synchronization | ExternalThreading. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

The following code example demonstrates the features of the Timer class.


using System;
using System.Threading;

class TimerExample
{
    static void Main()
    {
        // Create an event to signal the timeout count threshold in the
        // timer callback.
        AutoResetEvent autoEvent     = new AutoResetEvent(false);

        StatusChecker  statusChecker = new StatusChecker(10);

        // Create an inferred delegate that invokes methods for the timer.
        TimerCallback tcb = statusChecker.CheckStatus;

        // Create a timer that signals the delegate to invoke 
        // CheckStatus after one second, and every 1/4 second 
        // thereafter.
        Console.WriteLine("{0} Creating timer.\n", 
            DateTime.Now.ToString("h:mm:ss.fff"));
        Timer stateTimer = new Timer(tcb, autoEvent, 1000, 250);

        // When autoEvent signals, change the period to every
        // 1/2 second.
        autoEvent.WaitOne(5000, false);
        stateTimer.Change(0, 500);
        Console.WriteLine("\nChanging period.\n");

        // When autoEvent signals the second time, dispose of 
        // the timer.
        autoEvent.WaitOne(5000, false);
        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 Main.
            invokeCount  = 0;
            autoEvent.Set();
        }
    }
}


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

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.

This type is thread safe.

Community Additions

Show:
© 2014 Microsoft