Esbasic reusable. Net class library (07) -- callback timer icallbacktimer

Source: Internet
Author: User
  1. Origin:

For example, you may be able to clearly explain the purpose of the callback timer. Assume that my order system receives different types of orders. A After the system makes a comprehensive judgment based on the order type and other features A Order to be in 2 Method After seconds M1 Processing; B After the order has passed the same judgment, it is decided 10 Method After seconds M2 Processing, ...... . At this time, you can use a callback timer to manage the tasks that will be executed after a certain delay.

Of course, we can use a timer or the loop engine described earlier to implement this function, but we need to manually manage the registered scheduled callback task, in addition, it regularly checks whether each unprocessed order has reached the processing time. The callback timer has automatically helped us to do these things, and is still a common component unrelated to the specific application. We do not need to implement a specific class to do this again.

The image of the callback timer is as follows:

2.Applicable scenarios:

Design callback TimerEsbasic. Threading. Timers. icallbacktimerTo solve the following problems:

(1)The task (callback) needs to be executed after a certain interval of time.

(2)Different tasks may be delayed at different intervals.

(3)Different tasks may be processed in different ways.

(4)Callback latency does not need to be very precise.

The main problem to be solved by the callback timer is the first point. The next two points are also important features supported by the callback timer.

 

3Design ideas and implementation

IcallbacktimerThe interface is defined as follows: 

///   <Summary>
/// Icallbacktimer callback timer.
/// Note: The callback task is executed asynchronously on the workerthread of threadpool. Even if the target task throws an exception, the running of inotifytimer will not be affected.
///   </Summary>
Public   Interface   Icallbacktimer < T > : Icycleengine
{
Int Taskcount { Get ;}

///   <Summary>
/// Addcallback adds a callback task. The target task runs after spaninsecs. Run only once.
///   </Summary>
///   <Param name = "spaninsecs"> How many seconds to execute the task </Param>
///   <Param name = "_ callback"> Delegate the target method </Param>
///   <Param name = "_ callbackpara"> Parameters for calling the target method </Param>
///   <Returns> New task id </Returns>
Int Addcallback ( Int Spaninsecs, Cbgeneric < T > _ Callback, T _ callbackpara );

//


// removecallback deletes the target callback task.
//
void removecallback ( int taskid );

///   <Summary>
/// Removecallbackandaddnew deletes the target callback task and adds a new callback task.
///   </Summary>
Int Removecallbackandaddnew ( Int Taskidtoremoved, Int Spaninsecs, Cbgeneric < T > _ Newcallback, T _ newcallbackpara );

///   <Summary>
/// How long does getleftseconds wait for the target task to be called back for execution (s ). 0 is returned, indicating that the task does not exist or has been executed.
///   </Summary>
Int Getleftseconds ( Int Taskid );

//


// clear clears all callback tasks.
//
void clear ();
}

based on the preceding description of the callback timer, we can implement it using the loop engine. As you can see, icallbacktimer inherited icycleengine interface, this shows that we can use Start ,< /Span> stop method to control the running of the callback timer, and detectspaninsecs attribute to set the time interval for detecting the task status. Of course, detectspaninsecs the set value is better than the minimum latency interval of the callback task.

icallbacktimer interface generic parameters T indicates the type of parameters used for callback execution. The callback method must only accept one T type parameter, and no return value (for example, generic delegation cbgeneric ).

AddcallbackMethod returnsIntIndicates the unique ID of the added task. We can use this ID to query the time when the task was executed by the callback (GetleftsecondsMethod), or cancel the execution of the target callback task (RemovecallbackMethod ).

CallbacktimerImplementedIcallbacktimerInterface. Note the following points for its implementation:

(1)CallbacktimerInherited fromBasecycleengineIt uses the loop engine to perform cyclic detection of task status.

(2)To allow a timer to be called back in a multi-threaded environment,CallbacktimerThe internal set (Dictask.

(3)CallbacktimerUseCallbacktaskClass to encapsulate a scheduled callback task.

(4)Callback tasks are asynchronous in the background.ThreadpoolOfWorkerthread. Therefore, multiple callback tasks that meet the execution conditions will not be blocked, but will be executed almost simultaneously.

(5) In Dodetect In the implementation of the method, we first copy a task list and then perform Foreach Instead of directly This. dictask. Values Work Foreach This is because, when a callback is executed Addcallback/removecallback Modify This. dictask In This. dictask. Values Of Foreach It is not over yet. Foreach Will throw an exception.

4.Precautions for use

First, pay attention Getleftseconds The returned value is inaccurate. Because Callbacktimer During each loop detection (overwriting the base class Dodetect Method), modify each Callbacktask Of Leftseconds (Through Callbacktask Of Secondspassed Method ). So, Getleftseconds The method returns only an approximate rather than an exact value.

Second, callback execution is "one-time", that is, a registered callback task is executed only once or canceled.

Again, the callback task Timer allows the callback task to throw an exception during execution, but the exception is ignored by the callback timer. Therefore, if you want to handle this exception, you should capture this exception in the callback method.

Finally, because the callback task runs asynchronously in the background thread pool, if many callback tasks are executed simultaneously, the number of threads exceeds the number of threads in the background thread pool, in this case, some callback tasks will be further delayed.

 

5.Extension

Callback TimerIcallbacktimerThere are currently no extensions.

Note: The esbasic source code can be foundHttp://esbasic.codeplex.com/Download.

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.