C# Tips

Thread Timer

Advertisements

There are three timer controls in the .NET Framework:

If you are using Windows Forms and probably updating a UI, use System.Windows.Forms.Timer.

For server-based timer functionality, you might consider using System.Timers.Timer, which is also more accurate and has additional features.

The third one, System.Threading.Timer, uses a separate thread for it’s operation. If you need to do an asynchronous job periodically, it may be useful.

Using  System.Threading.Timer:


System.Threading.Timer timer;
timer = new System.Threading.Timer(new TimerCallback(DoSomething), null, 0, 1000);

DoSomething() executes at specified intervals(1000 ms here). Note that DoSomething() does not execute on the thread that created the timer; it executes on a ThreadPool thread supplied by the system.


private void DoSomething(object obj)
{
//it executes every second
}

To enable/disable timer, use Change() method:


timer.Change(Timeout.Infinite, Timeout.Infinite); //disable
timer.Change(0, 1000); //enable
Advertisements