Do not use Thread as a timer

Source: Internet
Author: User

It is often seen that many programs use Thread as a Timer (Timer), such as regularly checking data, regularly clearing cache or something.

Just like the following code

Code
 Thread t = new Thread (p =>
{
While (true)
{
// Do something... for example, refresh the data operation cache and other scheduled tasks
Thread. Sleep (10000 );
}
});
T. Start ();

Some friends may have noticed that this Thread often does not work normally on the high-pressure Asp.net website. Maybe this Thread will never get up again ....... then the scheduled task is ruined.

PS: If it is the main thread of the console (marked with STAThreadAttribute), it can recover and sleep normally.

Another reason is that every Thread is expensive and does not need to be used,

We recommend that you use System. Threading. Timer to execute scheduled tasks.

1) System. Threading. Timer is triggered by the Kernel-Mode, so no task is running.

2) Remember to place the Timer variable on the instance Member or static member of the class to avoid Timer GC in the Release mode (I have mentioned this in another article)

3) after the Timer execution is set for the Timer, if the second execution time is reached, the second execution will start even if the first execution is not completed, you can consider using the following two solutions to prevent conflicts between multiple executions:

A. set Timer to run only once. In the last sentence of the Timer method call, reset Timer. Change (int dueTime, int period );

B. Use a variable to indicate whether a timer is currently being executed. It is recommended to use InterLocked to represent an int variable.

 

PS: Not recommended

1) System. Timers. Timer is actually an encapsulation of System. Threading. Timer.

2) System. Windows. Forms. Timer, Based on Message Mechanism

PS: windows only considers thread switching for about 30 ms... and windows generally has several hundred threads --#

Related Article

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.