Search code examples
c#multithreadingeventsevent-handling

Event Handler that can be triggered every 100ms in C# automatically


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?


Solution

  • 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