Timer provides mechanism to execute method at specific
intervals. Dotnet Framework provides two types of Timers.
1.
System.Threading.Timer
System.Threading.Timer
is easiest and simplest to implement. We need to provide delegate to constructor
of timer object. We also need to provide other information like state, duetime
and period while creations of Timer object. Below is the Timer class constructor
signature.
public
Timer(TimerCallback callback, object state, int
dueTime, int period);
First
parameter is callback method which will repeatedly call at specified period.
Second parameter accepts value as an object to the method if you want to pass.
Third parameter accepts due time after that time your method will start
executing. The last parameter is period which will call method repeatedly at
specified period. Let’s have a look on below code.
using System.Threading;
public class MyClass
{
public static void RunSnippet()
{
Timer t1 = new Timer(HelloMessage, null, 2000, 500);
Console.ReadLine();
t1.Dispose();
}
public static void HelloMessage(object obj)
{
Console.WriteLine("Hello World...");
}
}
As per above example
the HelloMessage will get called every 500ms after 2000ms have elapsed. The
dispose method will stop the timer as well remove from memory. Timer internally
uses ThreadPool to execute callback method.
2.
System.Timers.Timer
System.Timers.Timer is almost similar to
System.Threading.Timer. System.Timers.Timer calls event repeatedly on certain interval.
This timer also known as server based timer. This timer is used in
MultiThreading to call Elapsed events. System.Timers.Timer provides more
properties and methods compare to System.Threading.Timer. Below are some important properties of System.Timers.Timer.
Interval –
Specifies the interval time to raise the elapsed event.
Elapsed –
Specifies event (callback delegate)
Enabled –
Used to start/stop timer.
Start –
Used to start timer.
Stop –
Used to stop timer.
using System.Timers;
public class MyClass
{
public static void RunSnippet()
{
Timer t1 = new Timer();
t1.Interval = 500;
t1.Elapsed += new ElapsedEventHandler(t1_Elapsed);
t1.Start();
Console.ReadLine();
t1.Stop();
Console.ReadLine();
t1.Dispose();
}
static void t1_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("Hello World...");
}
}
The t1_Elapsed event will automatically get called every
500ms after starting t1 timer.
See Also -
Lock Statement - Threading
Monitor.Enter/Monitor.Exit Statement - Threading
Mutex - Threading
Semaphore - Threading
Monitor.Enter/Monitor.Exit Statement - Threading
Mutex - Threading
Semaphore - Threading
No comments:
Post a Comment