Share via


Timer

Timers are lightweight objects that enable you to specify a delegate to be called at a specified time. A thread in the thread pool performs the wait operation.

Using the Timer class is straightforward. You create a Timer, passing a TimerCallback delegate to the callback method, an object representing state that will be passed to the callback, an initial raise time, and a time representing the period between callback invocations. To cancel a pending timer, call the Timer.Dispose function.

Note   There is also a System.Windows.Forms.Timer class. That class is based on operating system timer support, and if you are not pumping messages on the thread, your timer will not occur. This makes the System.Threading.Timer more useful in many scenarios.

The following simple code example demonstrates the use of a Timer.

Imports System
Imports System.Threading
Imports Microsoft.VisualBasic

Public Class TimerTest
   
   Public timerevent As ManualResetEvent
   
   Public Sub New()
      timerevent = New ManualResetEvent(False)
      Dim timer As New Timer(New TimerCallback(AddressOf Me.TimerMethod), Nothing, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5))
      Dim TickTimer As New Timer(New TimerCallback(AddressOf Me.Tick), Nothing, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1))
   End Sub 'New
   
   Public Sub TimerMethod(state As Object)
      Console.WriteLine(ControlChars.Cr + "The Timer invoked this method.")
      timerevent.Set()
   End Sub 'TimerMethod
   
   Public Sub Tick(state As Object)
      Console.Write(".")
   End Sub 'Tick
   
   Public Shared Sub Main()
      Dim test As New TimerTest()
      Console.WriteLine("The timer has started and will count for five seconds.")
      test.timerevent.WaitOne()
      Console.WriteLine("...and control returned to the primary thread.")
   End Sub 'Main
End Class 'TimerTest
[C#]
using System;
using System.Threading;

public class TimerTest{
   
   public ManualResetEvent timerevent;

   public TimerTest(){

      timerevent = new ManualResetEvent(false);

      Timer timer = new Timer(
         new TimerCallback(this.TimerMethod),
         null, 
         TimeSpan.FromSeconds(5), 
         TimeSpan.FromSeconds(5)
      );

      Timer TickTimer = new Timer(
         new TimerCallback(this.Tick),
         null, 
         TimeSpan.FromSeconds(1), 
         TimeSpan.FromSeconds(1)
      );

   }

   public void TimerMethod(object state){
      Console.WriteLine("\rThe Timer invoked this method.");
      timerevent.Set();
   }

   public void Tick(object state){
      Console.Write(".");
   }

   public static void Main(){
      TimerTest test = new TimerTest();
      Console.WriteLine("The timer has started and will count for five seconds.");
      test.timerevent.WaitOne();
      Console.WriteLine("...and control returned to the primary thread.");
   }
}

See Also

Threading Objects and Features | Timer