1

Is there a way to trigger an event handler every 100ms in C# automatically without any call?

I need that event handler to trigger a function every 100ms or after any fixed time interval so as to process something. I am not able to figure out a way to do that. Can you help me out with this?

  • 1
    What you are describing is a *timer*. There are a [bunch of different timers](https://stackoverflow.com/questions/10317088/why-there-are-5-versions-of-timer-classes-in-net) in c#, depending on your exact need. – JonasH Jun 09 '23 at 07:06
  • note that all common timers have a resolution of ~16ms by default. – JonasH Jun 09 '23 at 07:07

1 Answers1

1

You can use DispatcherTimer

   DispatcherTimer updateTimer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 0, 0, 100) };
   updateTimer.Tick += new EventHandler(UpdateHandler);
   updateTimer.Start();

And you event handler should look something like this

 private void UpdateHandler(object sender, EventArgs e)
 {
      // Your Logic
 }

After that you event will be triggered every 100 ms.

Check the documentation from windows https://learn.microsoft.com/en-us/dotnet/api/system.windows.threading.dispatchertimer?view=windowsdesktop-7.0

DonMiguelSanchez
  • 376
  • 3
  • 15
  • 1
    "you[r] event will be triggered every 100 ms" - not strictly true. The Windows internal timer does 64 events per second, so, at best, you can get a timer down to once every 15.625 millisecond. So a 100 ms timer will fire between 93.75 and 109.375 ms or at every 109.375 ms, depending on how it is implemented. – Enigmativity Jun 12 '23 at 06:37