Share via


Timer Class

Microsoft Silverlight will reach end of support after October 2021. Learn more.

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

Inheritance Hierarchy

System.Object
  System.Threading.Timer

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

Syntax

'Declaration
<ComVisibleAttribute(True)> _
Public NotInheritable Class Timer _
    Implements IDisposable
[ComVisibleAttribute(true)]
public sealed class Timer : IDisposable

The Timer type exposes the following members.

Constructors

  Name Description
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Timer(TimerCallback) Initializes a new instance of the Timer class with an infinite interval and an infinite due time, using the newly created Timer object as the state object.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Timer(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 Silverlight for Windows PhoneSupported by Xbox 360 Timer(TimerCallback, Object, Int64, Int64) Initializes a new instance of the Timer class, using 64-bit signed integers to measure time intervals.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Timer(TimerCallback, Object, TimeSpan, TimeSpan) Initializes a new instance of the Timer class, using TimeSpan values to measure time intervals.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Timer(TimerCallback, Object, UInt32, UInt32) Initializes a new instance of the Timer class, using 32-bit unsigned integers to measure time intervals.

Top

Methods

  Name Description
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Change(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 Silverlight for Windows PhoneSupported by Xbox 360 Change(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 Silverlight for Windows PhoneSupported by Xbox 360 Change(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 Silverlight for Windows PhoneSupported by Xbox 360 Change(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 methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Dispose() Releases all resources used by the current instance of Timer.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Dispose(WaitHandle) Releases all resources used by the current instance of Timer and signals when the timer has been disposed of.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Finalize Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetType Gets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToString Returns a string that represents the current object. (Inherited from Object.)

Top

Remarks

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 that is 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 by 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. To receive a signal when the timer is disposed, use the Dispose(WaitHandle) method overload that takes a WaitHandle. The WaitHandle is signaled when the timer has been disposed.

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 scenarios in which the user interface must be updated, because its callbacks do not occur on the user interface thread. System.Windows.Threading.DispatcherTimer is a better choice in those scenarios, because its events are raised on the user interface thread.

Examples

The following example demonstrates the features of the Timer class. This example creates a timer, uses the Change method to change its interval, and then uses the Dispose method to destroy it.

The example displays its output in a TextBlock on the UI thread. To access the TextBlock from the callback thread, the example uses the Dispatcher property to obtain a Dispatcher object for the TextBlock, and then uses the Dispatcher.BeginInvoke method to make the cross-thread call.

Imports System.Threading

' The following Imports are not required for the timer. They merely simplify 
' the code.
Imports System.Windows.Controls
Imports System.Windows.Input

' The Example class holds a reference to the timer, and contains the 
' event handler for the MouseLeftButtonUp events that control the demo.
'
Public Class Example

   ' The Shared Demo method sets the starting message and creates an 
   ' instance of Example, which hooks up the handler for the MouseLeftButtonUp
   ' event.
   Public Shared Sub Demo(ByVal outputBlock As TextBlock)

      outputBlock.Text &= "Click to create the timer." & vbLf
      Dim dummy As New Example(outputBlock)

   End Sub


   ' Instance data for the demo.
   Private phase As Integer = 0
   Private t As Timer

   Public Sub New(ByVal outputBlock As TextBlock)

      ' Hook up the mouse event when a new Example object is created. Note
      ' that this keeps garbage collection from reclaiming the Example 
      ' object.
      AddHandler outputBlock.MouseLeftButtonUp, AddressOf Me.MouseUp

   End Sub

   Private Sub MouseUp(ByVal sender As Object, ByVal e As MouseButtonEventArgs)

      Dim outputBlock As TextBlock = CType(sender, TextBlock)

      If phase = 0 Then
         ' On the first click, create the timer.
         outputBlock.Text &= vbLf & "Creating the timer at " & _
            DateTime.Now.ToString("h:mm:ss.fff") & _
            ", to start in 1 second with a half-second interval." & vbLf & _
            "Click to change the interval from 1/2 second to 1 second." & vbLf & vbLf

         ' Create a timer that invokes the callback method after one second 
         ' (1000 milliseconds) and every 1/2 second thereafter. The TextBlock
         ' that is used for output is passed as the state object. Visual Basic 
         ' infers the delegate type, as if you had typed the following:
         '     New TimerCallback(AddressOf MyTimerCallback)
         ' 
         t = New Timer(AddressOf MyTimerCallback, outputBlock, 1000, 500)

      ElseIf phase = 1 Then
         ' On the next click, change the timer interval to every second.
         outputBlock.Text &= vbLf & "Changing the interval to one second." & vbLf & _
            "Click to destroy the timer." & vbLf & vbLf

         t.Change(0, 1000)

      Else
         ' On the last click, destroy the timer and shut down the demo.
         outputBlock.Text &= vbLf & "Destroying the timer." & vbLf & _
            "Refresh the page to run the demo again."
         RemoveHandler outputBlock.MouseLeftButtonUp, AddressOf Me.MouseUp

         t.Dispose()

      End If

      phase += 1

   End Sub


   ' The shared callback method is invoked on a ThreadPool thread by the Timer. 
   ' The state object is passed to the callback method on each invocation. In this
   ' example, the state object is the TextBlock that displays output. In order to
   ' update the TextBlock object, which is on the UI thread, you must make the  
   ' cross-thread call by using the Dispatcher object that is associated with the 
   ' TextBlock.
   Private Shared Sub MyTimerCallback(ByVal state As Object)

      Dim outputBlock As TextBlock = CType(state, TextBlock)
      Dim msg As String = DateTime.Now.ToString("h:mm:ss.fff") & _
                          " MyTimerCallback was called." & vbLf

      outputBlock.Dispatcher.BeginInvoke(displayHelper, outputBlock, msg)

   End Sub

   ' The DisplayOutput helper method and its delegate, displayHelper, are used by
   ' the BeginInvoke method of the Dispatcher object.
   Private Shared displayHelper _
                    As New Action(Of TextBlock, String)(AddressOf DisplayOutput)
   Private Shared Sub DisplayOutput(ByVal tb As TextBlock, ByVal msg As String)
      tb.Text &= msg
   End Sub

End Class

' This example produces output similar to the following:
'
'Click to create the timer.
'
'Creating the timer at 3:17:36.980, to start in 1 second with a half-second interval.
'Click to change the interval from 1/2 second to 1 second.
'
'3:17:38.072 MyTimerCallback was called.
'3:17:38.586 MyTimerCallback was called.
'3:17:39.101 MyTimerCallback was called.
'3:17:39.580 MyTimerCallback was called.
'
'Changing the interval to one second.
'Click to destroy the timer.
'
'3:17:39.656 MyTimerCallback was called.
'3:17:40.689 MyTimerCallback was called.
'
'Destroying the timer.
'Refresh the page to run the demo again.
using System;
using System.Threading;

// The following Imports are not required for the timer. They merely simplify 
// the code.
using System.Windows.Controls;
using System.Windows.Input;

// The Example class holds a reference to the timer, and contains the 
// event handler for the MouseLeftButtonUp events that control the demo.
//
public class Example
{
   // The static Demo method sets the starting message and creates an 
   // instance of Example, which hooks up the handler for the MouseLeftButtonUp
   // event.
   public static void Demo(TextBlock outputBlock)
   {
      outputBlock.Text += "Click to create the timer.\n";
      Example dummy = new Example(outputBlock);
   }


   // Instance data for the demo.
   private int phase = 0;
   private Timer t;

   public Example(TextBlock outputBlock)
   {
      // Hook up the mouse event when a new Example object is created. Note
      // that this keeps garbage collection from reclaiming the Example 
      // object.
      outputBlock.MouseLeftButtonUp += new MouseButtonEventHandler(this.MouseUp);
   }

   private void MouseUp(object sender, MouseButtonEventArgs e)
   {
      TextBlock outputBlock = (TextBlock) sender;

      if (phase==0)
      {
         // On the first click, create the timer.
         outputBlock.Text += "\nCreating the timer at " + 
               DateTime.Now.ToString("h:mm:ss.fff") + 
               ", to start in 1 second with a half-second interval.\n" +
               "Click to change the interval from 1/2 second to 1 second.\n\n";

         // Create a timer that invokes the callback method after one second 
         // (1000 milliseconds) and every 1/2 second thereafter. The TextBlock
         // that is used for output is passed as the state object. C# infers the 
         // delegate type, as if you had typed the following:
         //     new TimerCallback(MyTimerCallback)
         // 
         t = new Timer(MyTimerCallback, outputBlock, 1000, 500);

      }
      else if (phase==1)
      {
         outputBlock.Text += "\nChanging the interval to one second.\n" +
                             "Click to destroy the timer.\n\n";
         t.Change(0, 1000);
      }
      else
      {
         // On the last click, destroy the timer and shut down the demo.
         outputBlock.Text += "\nDestroying the timer.\n" + 
                             "Refresh the page to run the demo again.";
         outputBlock.MouseLeftButtonUp -= new MouseButtonEventHandler(this.MouseUp);

         t.Dispose();
      }

      phase += 1;
   }


   // The static callback method is invoked on a ThreadPool thread by the Timer. 
   // The state object is passed to the callback method on each invocation. In this
   // example, the state object is the TextBlock that displays output. In order to
   // update the TextBlock object, which is on the UI thread, you must make the  
   // cross-thread call by using the Dispatcher object that is associated with the 
   // TextBlock.
   private static void MyTimerCallback(object state)
   {
      TextBlock outputBlock = (TextBlock) state;
      string msg = DateTime.Now.ToString("h:mm:ss.fff") + " MyTimerCallback was called.\n";

      outputBlock.Dispatcher.BeginInvoke(delegate () { outputBlock.Text += msg; });
   }
}

/* This example produces output similar to the following:

Click to create the timer.

Creating the timer at 3:40:17.712, to start in 1 second with a half-second interval.
Click to change the interval from 1/2 second to 1 second.

3:40:18.820 MyTimerCallback was called.
3:40:19.335 MyTimerCallback was called.
3:40:19.849 MyTimerCallback was called.

Changing the interval to one second.
Click to destroy the timer.

3:40:20.317 MyTimerCallback was called.
3:40:21.331 MyTimerCallback was called.

Destroying the timer.
Refresh the page to run the demo again.
 */

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Thread Safety

This type is thread safe.