1

In my C# project I want to execute a function periodically every 30ms. First I tried the .net Timers, but I have found out that these timer have no more accuracy then 15ms due to Windows OS restrictions. I read in some stackoverflow entries that the only way in Windows is to use a Multimedia timer. (or you change some system clock settings, what I don't want to do).I have seen some code examples but as I am a very fresh junior programmer they were too complex for me and I even didn't get where to insert my Periodic function code inside.

  1. Is it really true that I can achieve 1ms accuracy with Multimedia timer on a Windows OS?

  2. If yes, can anyone give me a simple example how I can use a Multimedia timer to execute my function periodically? My code is running on a Windows 2019 Server OS.

This is the code I have used till now: (Bad accuracy 15ms)

System.Timers.Timer Periodic_timer = new System.Timers.Timer();
public void InitializeTimer_Periodic_timer()
{            
    Periodic_timer.Elapsed += new ElapsedEventHandler(OnTimedEvent_Periodic_timer);
    Periodic_timer.Interval = 30;
    Periodic_timer.Start();
}

private void OnTimedEvent_Periodic_timer(object sender, EventArgs e)
{
    Periodic_function();
}
Florian
  • 1,019
  • 6
  • 22
Dargento
  • 31
  • 3
  • 1
    Does this answer your question? [C# Timer for Millisecond Waits](https://stackoverflow.com/questions/9891879/c-sharp-timer-for-millisecond-waits) – Filburt May 04 '23 at 12:09
  • You can [increase the timer frequency](https://stackoverflow.com/questions/58969311/increase-timer-resolution-high-resolution-on-windows-without-ntsettimerresolut), but this is often frowned upon since it is a system wide change that impact power usage. I'm not sure if the multimedia timer just does this or if it does something else. If you want something simple to use it is often useful to start searching nuget, [first hit for multimedia timer](https://www.nuget.org/packages/MultimediaTimer) – JonasH May 04 '23 at 12:31
  • I've not used this frequent a timer interval before, but regardless of which implementation is used, one has to consider that the code triggered in the interval may take longer to run than the interval duration itself. This would mean the solution has to be multi-threaded. My 'gut' feeling would be to at least run the triggered code in its own thread (which may be problematic if there's a class field it's meant to check/update state with), or even a separate process if possible. The triggered code should be completely isolated if possible, which is easier said than done for this type of thing. – majixin May 04 '23 at 12:45

0 Answers0