How to use a timer in C#?

In C#, you can use the System.Timers.Timer class or System.Threading.Timer class to create and use timers.

  1. Utilize the System.Timers.Timer class:
  2. Add the namespace at the top of the code: using System.Timers;
  3. Create a Timer object: Timer timer = new Timer();
  4. Set the time interval (in milliseconds): timer.Interval = 1000; (indicating triggering every 1 second)
  5. Bind the method to be executed: timer.Elapsed += TimerElapsedMethod; (TimerElapsedMethod is the custom method name)
  6. Start the timer: timer.Start();
  7. Method executed after the timer triggers: private static void TimerElapsedMethod(object sender, ElapsedEventArgs e) { /* Code execution */ }
  8. Stop the timer: timer.Stop();
  9. Use the System.Threading.Timer class:
  10. Add the namespace “using System.Threading;” at the top of the code.
  11. Create a Timer object: Timer timer = new Timer(TimerCallbackMethod, null, 0, 1000);
  12. Bind the method to be executed: private static void TimerCallbackMethod(Object obj) { /* Code to be executed */ }
  13. The first parameter is a method of type TimerCallback delegate, the second parameter is the object passed to the method, the third parameter is the time delay before starting the timer (in milliseconds), and the fourth parameter is the interval time of the timer (in milliseconds).
  14. Stop the timer: timer.Change(Timeout.Infinite, Timeout.Infinite);

When using the System.Timers.Timer class, it is important to utilize the System.Windows.Forms.Application.Run method to start the message loop in a Windows forms application. Without the message loop, the Elapsed event of the timer will not be triggered. However, when using the System.Threading.Timer class, there is no need for a message loop.

bannerAds