I have to execute a function periodically for a specific time in my windows service app. The function is reading out a current value from a remote CNC machine. The function will be executed every 35 ms for 30 seconds. Normally the data reading takes 20-30 ms. (Changing with network and CNC machine conditions)

First I have used system timer, but I experienced that the accuracy of the timer is bad. I have also read in the internet that the accuracy is 10-15 ms.

-Finally I decided to execute the function in loop.

-I used a stopwatch to calculate function's execution time.

-I substracted this time from 35 ms,

I used the result for sleeping the thread --> So each time I should start the next function after 35ms. But later I noticed that the Thread.Sleep function is also not very accurate, so I am really confused how to proceed now. Is there any other accurate method to wait the program executing for any x ms's ? Or should I change my strategie completely? The accuaracy that I am looking for is 1-2 ms.

My code is

 public void Periodic()
  {
    while(period_over==false)
    {
    var watch = System.Diagnostics.Stopwatch.StartNew();        
    Read_Data_form_CNC();
    var elapsedMs = watch.ElapsedMilliseconds;
    Thread.Sleep(35-elapsedMs);
    }
  }
0

There are 0 best solutions below