0

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);
    }
  }
Dargento
  • 31
  • 3
  • 3
    1-2ms: consider switching to a real-time os and language. And make sure the hardware can do that kind of real- time accuracy. Any language that stops the world for GC would be out the window, I guess. – Fildor Apr 30 '23 at 10:06
  • Windows internal timer has a resolution of 64 times per second. You shouldn't expect Windows to be any better than 15.625 millisecond for accuracy. You're not going to get between 1 and 2 no matter what you try. – Enigmativity Apr 30 '23 at 11:01

0 Answers0