Repeating a function every few seconds
For this the System.Timers.Timer
works best
// Create a timer
myTimer = new System.Timers.Timer();
// Tell the timer what to do when it elapses
myTimer.Elapsed += new ElapsedEventHandler(myEvent);
// Set it to go off every five seconds
myTimer.Interval = 5000;
// And start it
myTimer.Enabled = true;
// Implement a call with the right signature for events going off
private void myEvent(object source, ElapsedEventArgs e) { }
See Timer Class (.NET 4.6 and 4.5) for details
Use a timer. There are 3 basic kinds, each suited for different purposes.
- System.Windows.Forms.Timer
Use only in a Windows Form application. This timer is processed as part of the message loop, so the the timer can be frozen under high load.
- System.Timers.Timer
When you need synchronicity, use this one. This means that the tick event will be run on the thread that started the timer, allowing you to perform GUI operations without much hassle.
- System.Threading.Timer
This is the most high-powered timer, which fires ticks on a background thread. This lets you perform operations in the background without freezing the GUI or the main thread.
For most cases, I recommend System.Timers.Timer.
Use a timer. Keep in mind that .NET comes with a number of different timers. This article covers the differences.