Thoughts on timer in. net threads

Source: Internet
Author: User
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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.