Timer Class
This page is specific to:.NET Framework Version:1.12.03.03.5Silverlight 34.0
.NET Framework Class Library
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)
Syntax

'Usage

Dim instance As Timer

'Declaration

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

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.

NoteNote:

The HostProtectionAttribute attribute applied to this class 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.

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

Examples

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

Imports Microsoft.VisualBasic
Imports System
Imports System.Threading

Public Class TimerExample

    <MTAThread> _
    Shared Sub Main()

        Dim autoEvent As New AutoResetEvent(False)
        Dim statusChecker As New StatusChecker(10)

        ' Create the delegate that invokes methods for the timer.
        Dim timerDelegate As TimerCallback = _
            AddressOf 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." & vbCrLf, _
            DateTime.Now.ToString("h:mm:ss.fff"))
        Dim stateTimer As Timer = _
                New Timer(timerDelegate, autoEvent, 1000, 250)

        ' When autoEvent signals, change the period to every 
        ' 1/2 second.
        autoEvent.WaitOne(5000, False)
        stateTimer.Change(0, 500)
        Console.WriteLine(vbCrLf & "Changing period." & vbCrLf)

        ' When autoEvent signals the second time, dispose of 
        ' the timer.
        autoEvent.WaitOne(5000, False)
        stateTimer.Dispose()
        Console.WriteLine(vbCrLf & "Destroying timer.")

    End Sub
End Class

Public Class StatusChecker

    Dim invokeCount, maxCount As Integer 

    Sub New(count As Integer)
        invokeCount  = 0
        maxCount = count
    End Sub

    ' This method is called by the timer delegate.
    Sub CheckStatus(stateInfo As Object)
        Dim autoEvent As AutoResetEvent = _
            DirectCast(stateInfo, AutoResetEvent)
        invokeCount += 1
        Console.WriteLine("{0} Checking status {1,2}.", _
            DateTime.Now.ToString("h:mm:ss.fff"), _
            invokeCount.ToString())

        If invokeCount = maxCount Then

            ' Reset the counter and signal to stop the timer.
            invokeCount  = 0
            autoEvent.Set()
        End If
    End Sub

End Class


Inheritance Hierarchy

System..::.Object
  System..::.MarshalByRefObject
    System.Threading..::.Timer
Thread Safety

This type is thread safe.

Platforms

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information

.NET Framework

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

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 3.0, 2.0, 1.0
See Also

Reference

Other Resources

Community Content

Be careful when the scheduled code takes longer than the timer's interval
Added by:Kristof Verbiest
Be very careful when the code that is executed by the timer takes longer to execute than the timer's interval. This may easily happen if the code contains a blocking call (such as a lock statement).
In this case, the timer will keep starting new threadpool threads (because there are no free threads). In the end, all threadpool threads will be used and this may cause serious problems.
You can work around this by setting your timer to be executed only once, and reset the timer after the code has executed.
You can find an example of this here:
http://kristofverbiest.blogspot.com/2008/08/timers-executing-task-at-regular.html
Use Dispose, when Timer no longer needed!
Added by:Harry Pfleger
As in the notes above, allways use the Dispose method, when the timer is no longer needed.
See why, running the following code once without t.Dispose(), and once with the t.Dispose():

using System;
using System.Threading;
public sealed class App
{
public static void Main()
{
Timer t = new Timer(M, null, 0, 2000);
Console.ReadLine();
//t.Dispose();
}
static void M(Object o)
{
Console.WriteLine("In M: " + DateTime.Now);
GC.Collect();
}
}
© 2009 Microsoft Corporation. All rights reserved.   Terms of Use | Trademarks | Privacy Statement
Page view tracker
Rate the Lightweight library
x
Lightweight builds on ScriptFree (loband) by adding features you've requested: a SearchBox and default code language selection.
Do you like the SearchBox?
Do you like the tabbed code blocks?
How useful is this topic?
Tell us more.
Thanks
x
You're helping to improve MSDN Online.
Feedback
Switch View
Classic
Lightweight Beta
ScriptFree
Switch View