16 July 2013

Real Time Timer in C#

In  Dot Net, following timers are not real time.

System.Windows.Forms.Timer
System.Timers.Timer
System.Threading.Timer

Means if you want to run your code at every 100 millisecond then above timer fire even around 110 millisecond or later. Windows is not a real time OS because of this .Net is also not a real time.

To create a real time timer in C# you have to write custom code that can hold CPU to run your code at right time.


class Program
{
   static void Main(string[] args)
  {
    Console.ReadLine();
    Console.WriteLine("Running");
    RealTimeTimerTest obj = new RealTimeTimerTest();
 
    obj.Run();
  }
}
 
public class RealTimeTimerTest
{
   List<DateTime> lst = new List<DateTime>();
  System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
 
  public void Run()
  {
    int Tick = 100;
    int Sleep = Tick - 20;
    long OldElapsedMilliseconds = 0;
    sw.Start();

    while (sw.IsRunning)
    {
      long ElapsedMilliseconds = sw.ElapsedMilliseconds;
      long mod = (ElapsedMilliseconds % Tick);

      if (OldElapsedMilliseconds != ElapsedMilliseconds && (mod == 0 || ElapsedMilliseconds > Tick))
      {

        //-----------------Do here whatever you want to do--------------Start
        lst.Add(DateTime.Now);
        //-----------------Do here whatever you want to do--------------End

        //-----------------Restart----------------Start
        OldElapsedMilliseconds = ElapsedMilliseconds;
        OldElapsedMilliseconds = 0;
        sw.Reset();
        sw.Start();
 
        System.Threading.Thread.Sleep(Sleep); 
         //-----------------Restart----------------End
      }
       
      //------------Must define some condition to break the loop here-----------Start

      if (lst.Count > 500)
      {
        Write();
        break;
      }
      //-------------Must define some condition to break the loop here-----------End
    }
  }

 
  private void Write()
  {
    System.IO.StreamWriter sw = new System.IO.StreamWriter("d:\\text.txt", true);
    foreach (DateTime dtStart in lst)
      sw.WriteLine(dtStart.ToString("HH:mm:ss.ffffff"));    sw.Close();
  }
}

//OUTPUT:
//03:15:55.503314
//03:15:55.603320
//03:15:55.703325
//03:15:55.803331
//03:15:55.903337
//03:15:56.003343
//03:15:56.103348
//03:15:56.203354
//03:15:56.303360
//03:15:56.403365
//03:15:56.503371
//.
//.
//.

No comments:

Post a Comment