Sunday, April 26, 2015

Create timer for non-windows application in C# in which long process is run

There are times when we need to create a timer for our codes, this can be done by following some simple structure like the following:

using System.Threading;

public class WebCrawler
{
  private Timer mTimer;
  
  public void Start()
  {
    mTimer = new Timer(OnTimerTicked, null, 0, 100);
  }

  public void Stop()
  {
    mTimer.Change(Timeout.Infinite, Timeout.Infinite);
  }

  private void OnTimerTicked(object state)
  {
    DoSomethingLong();
  }
}


The problem is the operation implemented in OnTimerTicked may take more than the timer interval (which is 100 milliseconds in the above example) to run. This is not desired as it may lead to memory corruption. The simple way to work around this is to fire the timer only once at the start, which will then invoke OnTimerTicked callback function, at the end of the OnTimerTicked callback, the timer can be reinvoked by calling its change() method, until flag change which cancel the timer's ticked operation. This is shown in the following code.

using System.Threading;

public class WebCrawler
{
  private Timer mTimer;
  private bool mIsWorking;
  
  public void Start()
  {
    mIsWorking=true;
    mTimer = new Timer(OnTimerTicked, null, 0, 100);
  }

  public void Stop()
  {
    mIsWorking = false;
    mTimer.Change(Timeout.Infinite, Timeout.Infinite);
  }

  private void OnTimerTicked(object state)
  {
    if(mIsWorking)
    {
      DoSomethingLong();
      mTimer.Change(100, Timeout.Infinite);
    }
  }
}

No comments:

Post a Comment