C # scheduled computing limit operation (timer)

Source: Internet
Author: User

In. NET Framework class library (FCL), the system. Threading namespace defines a Timer class, which is a commonly used timer. In fact, FCL provides the following Timers:

1. system. Threading. Timer

In actual development, this class is frequently used. Next we will focus on some of its basic concepts and application instances.

(1 ),Common Constructors

 
Public timer (timercallback callback, object state, int duetime, int period); Public timer (timercallback callback, object state, long duetime, long period); Public timer (timercallback callback, object state, timespan duetime, timespan period); Public timer (timercallback callback, object state, uint duetime, uint period );

Parameter description:

A,Callback: Wangwen business, certainly indicates a callback, which is a method that identifies the thread callback to be performed by a thread pool. Of course, its type must match the system. Threading. timercallback delegate type, as shown below:

 
Public Delegate void timercallback (Object State );

B,State: The status data passed to the callback method each time the callback method is called. If not, it can be null;

C,Duetime: The number of milliseconds to wait before the first callback method is called. If you want to call the callback method immediately, set this parameter to 0.

D,Period: Specifies the number of milliseconds to wait before each callback method is called (the interval between the next call and the current CALL ). If timeout. Infinite (or-1) is passed for this parameter, the thread pool thread only calls the callback method once (no timer is required ).

 

(2 ),Basic working principle

Internally (the original article should be in CLR), the thread pool uses only one thread for all timer objects. This thread knows when the next timer object will expire (how long the timer will be triggered ). When the next timer object expires, the thread will wake up and call the queueuserworkitem of threadpool internally to add a work item to the queue of the thread pool so that your callback method can be called.

Note: If the execution time of the callback method is long, the timer may be triggered again when the previous callback is not completed. (For tasks with a long execution time, the thread pool is usually not used in actual development, but directly use a new thread ). This may cause multiple thread pool threads to call your method at the same time (overlapping Methods overwrite ?). To solve this problem, Jeffrey Richter recommends that we use timer as follows:

A. Specify timeout. Infinite for period. In this way, the timer is triggered only once;

B. In the callback method, call the timer change method to specify a new duetime and specify timeout. Infinite for the period. Several overloaded versions of the change method:

 
Public bool change (INT duetime, int period); Public bool change (long duetime, long period); Public bool change (timespan duetime, timespan period); Public bool change (uint duetime, uint period );

Timer also has a dispose method that allows you to completely cancel the timer.

(3 ),ExampleCode

Internal static class timerdemo {Private Static timer s_timer; public static void main () {console. writeline ("main thread: starting a timer"); Using (s_timer = new timer (computeboundop, 5, 0, timeout. infinite) {console. writeline ("main thread: doing other work here... "); thread. sleep (10000); // simulating other work (10 seconds)} // calldispose to cancel the timer now console. read ();} // This method's signature must match the timercallback delegate Private Static void computeboundop (object state) {// This method is executed by a thread pool thread console. writeline ("in computeboundop: State = {0}", State); thread. sleep (1000); // simulates other work (1 second) // have the timer call this method again in 2 seconds s_timer.change (2000, timeout. infinite); // when this method returns, the thread goes back // to the pool and waits for another work item }}

This example is the source code in <CLR via C #>. Although it is simple, it runs through the creation of timer, and timer regularly works to destroy the entire lifecycle of timer. We can use try finally to replace the using statement and explicitly call the dispose method in the finally statement block. Note,ProgramOutputFour times"In computeboundop: State = 5", you may want to think about why only four times. If we take this line of the main method:

 
Thread. Sleep (10000); // simulating other work (10 seconds)

Comment out, the program sometimes throws"The program cannot access released objects.", And the output results may be different each time. This is because the using statement cannot ensure that the static timer is immediately recycled by the garbage collector. Try it yourself.

 

2. system. Timers. Timer

This class is said to be basically the "full-capacity by-product" encapsulated by system. Threading. Timer ". When the timer is triggered upon expiration, the CLR will place the event in the queue of the thread pool. This class is derived from the component class of system. componentmodel. It allows vs to place the timer object on the design plane and expose its attributes and events (isn't it a control, isn't it ?).

 

3. system. Windows. Forms. Timer

Constructing an instance of this class is equivalent to telling windows to associate a timer with the call thread. When this timer is triggered, Windows injects a timely message into the thread's message queue. The thread must execute a message pump to extract these messages and dispatch them to the desired callback method. Note that all these tasks are completed by only one thread. The thread that sets the timer is the thread that executes the callback method. This also means that your timer method will not be executed concurrently by multiple threads.

 

4. system. Windows. Threading. dispatchertimer

This class is equivalent to the timer of system. Windows. Forms in the WPF and Silverlight applications. In general, this class is a vest of system. Windows. Forms timer under WPF and Silverlight. It's not a day or two in the MS technology field because I'm good at changing the heads and dressing old wine.

 

In Jeffrey Richter's <CLR via C #>, the timer was very refined, and he said, "In fact, I personally never use the system. timers. timer class. We recommend that you do not use it either. "His attitude is very interesting. I have used a lot of such classes, and I have never made any mistakes. Even a "shanzhai" or "vest" is not always useless.

 

Refer:

Jeffrey Richter <CLR via C #>

Http://msdn.microsoft.com/zh-cn/library/system.threading.timer.aspx

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.