Home  • Programming • Microsoft .NET Framework

Thread Timer

There are three timer controls in the .NET Framework: A Windows-based timer, which is always in the Visual Studio Toolbox (System.Windows.Forms.Timer) A server-based timer, which you can add to the Visual Studio Toolbox (System.Timers.Timer) A thread timer, which is available programmatically (System.Threading.Timer) 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

Comments 0


Share

Copyright © 2024. Powered by Intellect Software Ltd