Recently, the timer of the thread used in the project is called the Timer. Threading. timer class. The following is a simple example.
Using System. Threading;
Using System;
Public class Sample
{
Public static void Main ()
{
TestException test = new TestException ();
Test. Start ();
Console. Read ();
}
}
Public class TestException
{
Private Timer workerTimer;
Private TimerCallback timerCallback;
Public TestException ()
{
TimerCallback = new TimerCallback (Working );
WorkerTimer = new Timer (timerCallback, null, Timeout. Infinite, Timeout. Infinite );
}
Public void Start ()
{
WorkerTimer. Change (2000,2000 );
}
Public void Stop ()
{
WorkerTimer. Change (Timeout. Infinite, Timeout. Infinite );
}
/// This method throws an exception
Private void WorkMethod ()
{
// Console. WriteLine ("executed ");
Throw new Exception ("exceptions I throw myself ");
}
Private void Working (object state)
{
Try
{
// Stop timer first and start timer
WorkerTimer. Change (Timeout. Infinite, Timeout. Infinite );
Console. WriteLine ("executed ");
WorkMethod ();
} Catch (Exception e)
{
Console. WriteLine (e. ToString ());
}
Finally
{
WorkerTimer. Change (2000,2000 );
}
}
}
The above code is simple to use. But there are several points to note: 1. if an exception is thrown within the Timer execution method, timer will not be executed. So, as shown above, the exception is handled in the method. In this way, timer can be executed normally.
2. gc of Timer is collected by gc if timer is not called.