Windows apps
Collapse the table of content
Expand the table of content
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 on a thread pool thread at specified intervals. This class cannot be inherited.

To browse the .NET Framework source code for this type, see the Reference Source.

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

System.Object
  System.MarshalByRefObject
    System.Threading.Timer

<ComVisibleAttribute(True)>
<HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization := True,
	ExternalThreading := True)>
Public NotInheritable Class Timer
	Inherits MarshalByRefObject
	Implements IDisposable

NameDescription
System_CAPS_pubmethodTimer(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.

System_CAPS_pubmethodTimer(TimerCallback, Object, Int32, Int32)

Initializes a new instance of the Timer class, using a 32-bit signed integer to specify the time interval.

System_CAPS_pubmethodTimer(TimerCallback, Object, Int64, Int64)

Initializes a new instance of the Timer class, using 64-bit signed integers to measure time intervals.

System_CAPS_pubmethodTimer(TimerCallback, Object, TimeSpan, TimeSpan)

Initializes a new instance of the Timer class, using TimeSpan values to measure time intervals.

System_CAPS_pubmethodTimer(TimerCallback, Object, UInt32, UInt32)

Initializes a new instance of the Timer class, using 32-bit unsigned integers to measure time intervals.

NameDescription
System_CAPS_pubmethodChange(Int32, Int32)

Changes the start time and the interval between method invocations for a timer, using 32-bit signed integers to measure time intervals.

System_CAPS_pubmethodChange(Int64, Int64)

Changes the start time and the interval between method invocations for a timer, using 64-bit signed integers to measure time intervals.

System_CAPS_pubmethodChange(TimeSpan, TimeSpan)

Changes the start time and the interval between method invocations for a timer, using TimeSpan values to measure time intervals.

System_CAPS_pubmethodChange(UInt32, UInt32)

Changes the start time and the interval between method invocations for a timer, using 32-bit unsigned integers to measure time intervals.

System_CAPS_pubmethodCreateObjRef(Type)

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.(Inherited from MarshalByRefObject.)

System_CAPS_pubmethodDispose()

Releases all resources used by the current instance of Timer.

System_CAPS_pubmethodDispose(WaitHandle)

Releases all resources used by the current instance of Timer and signals when the timer has been disposed of.

System_CAPS_pubmethodEquals(Object)

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_pubmethodGetHashCode()

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethodGetLifetimeService()

Retrieves the current lifetime service object that controls the lifetime policy for this instance.(Inherited from MarshalByRefObject.)

System_CAPS_pubmethodGetType()

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_pubmethodInitializeLifetimeService()

Obtains a lifetime service object to control the lifetime policy for this instance.(Inherited from MarshalByRefObject.)

System_CAPS_pubmethodToString()

Returns a string that represents the current object.(Inherited from Object.)

System_CAPS_noteNote

To view the .NET Framework source code for this type, see the Reference Source. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructions.

Use a TimerCallback delegate to specify the method you want the Timer to execute. The signature of the TimerCallback delegate is:

Sub TimerCallback(state As Object)

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.

System_CAPS_tipTip

The .NET Framework Class Library includes four classes named Timer, each of which offers different functionality:

  • 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, 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. 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, a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. 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, an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.

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). The Timer class has the same resolution as the system clock. 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. You can change the due time and period, or disable the timer, by using the Change method.

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

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

The following example defines a StatusChecker class that includes a CheckStatus method whose signature is the same as the TimerCallback delegate. 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. 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.

The application thread creates the timer, which waits one second and then executes the CheckStatus callback method every 250 milliseconds. The application thread then blocks until the AutoResetEvent object is signaled. When the CheckStatus callback method executes maxCount times, it calls the AutoResetEvent.Set method to set the state of the AutoResetEvent object to signaled. The first time this happens, the application thread calls the Change(Int32, Int32) method so that the callback method now executes every half second. It once again blocks until the AutoResetEvent object is signaled. When this happens, the timer is destroyed by calling its Dispose method, and the application terminates.

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.

Universal Windows Platform
Available since 8.1
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1

This type is thread safe.

Return to top
Show:
© 2016 Microsoft