June 29, 2012

System.Threading.Timer extension methods

The methods of the System.Threading.Timer are not particularly intuitive. Wrote these set of extension methods to make them a bit easier to use:

public static class TimerExtensions
{
 
  /// <summary>
  /// Stop the timer. 
  /// </summary>
  /// <param name="timer"></param>
  public static void Stop(this System.Threading.Timer timer)
  {
    timer.Change(Timeout.Infinite, Timeout.Infinite);
  }
 
  /// <summary>
  /// Start the timer as a periodic timer.  
  /// </summary>
  /// <param name="timer">target timer</param>
  /// <param name="periodMs">Delay imbetween TimerCallback invokations.
  /// Period is expressed in milliseconds </param>
  public static void StartPeriodic(this System.Threading.Timer timer, int periodMs)
  {
      // Note that timer.Change(Timeout.Infinite, periodMs); does not work!
      timer.Change(periodMs, periodMs);
  }
  /// <summary>
  /// Start the timer as a once only timer. 
  /// </summary>
  /// <param name="timer">target timer</param>
  /// <param name="periodMs">Period before the single invokation of the TimerCallback, 
  /// expressed in milliseconds </param>
  public static void StartOneTime(this System.Threading.Timer timer, int periodMs)
  {
    timer.Change(periodMs, Timeout.Infinite);
  } 
then the timer can be created, started and stopped very simply:
Timer timer = new Timer(new TimerCallback(TimerProc));
...
timer.StartPeriodic(500);
...
timer.Stop();

Don't forget the timer delegate:
// The Timer delegate to be invoked on a callback (from 
// another thread)
private void TimerProc(object obj)
{
    // Careful! callback occurs on another thread
}

Don't forget to dispose of the timer:

private void DisposeTimer()
{
    if (this.timer != null)
    {
        this.timer.Dispose();
        this.timer = null;
    }
}

No comments: