C # timer Improvement

Source: Internet
Author: User

Http://www.cnblogs.com/alala666888/archive/2012/03/15/2397704.html

C # There are three timers, one of which can only be used in windows such as winform.ProgramOnly system is available in the background. timers. timer and system. threading. timer, but these two timers are not complete, and some special requirements we encounter in our business cannot be met, such as timing callback cannot be executed at the same time. So I spent some time packaging two new timers, one supporting task serialization (the timer delegate only one execution at a time ), A fixed latency is supported (to ensure that the time between the execution of the last task and the execution start of this task is constant ).

1. Constant Frequency timer (support for serialization ).
Encapsulated fixedratetimer class:

C #

     ///   <Summary>  
/// Constant Frequency Timer
/// </Summary>
Public Class Fixedratetimer
{
/// <Summary>
/// Constructor
/// </Summary>
/// <Param name = "start"> How long will the execution start after startup delay? </Param>
/// <Param name = "interval"> The time from the start of the next execution </Param>
/// <Param name = "action"> Task Delegation </Param>
/// <Param name = "state"> Task status parameters </Param>
/// <Param name = "concurrent"> Parallelism allowed?
/// <Remarks> If parallel execution is allowed, several tasks may be executed simultaneously at the same time;
/// If not, this task is ignored when the new task finds that the previous task is running. </Remarks>
/// </Param>
Public Fixedratetimer (timespan start, timespan interval, timercallback action,
Object State = Null , Bool Concurrent = False )
{
_ Action = action;
_ Isconcurrent = concurrent;

_ Start = start;
_ Interval = interval;
_ State = State;
}

Private Void Timeraction ( Object S)
{
// Increase the number of ongoing tasks
Interlocked. increment ( Ref _ Jobcount );
If (! _ Isconcurrent)
{
// : Tasks cannot be executed in parallel, so they must be serialized.

// When no task is executed (_ isrunning = 0), the status changes to running (_ isrunning = 0 ),
// Then start executing the new task, becauseCodeIt may be executed in multiple threads, so atomic operations are used.
If (Interlocked. compareexchange ( Ref _ Isrunning, 1 , 0 ) = 0 )
{
_ Action (s );
// Change the status to no task running
Interlocked. Exchange ( Ref _ Isrunning, 0 );
}
}
Else
{
// No serial constraints, direct execution
_ Action (s );
}
// Reduce the number of ongoing tasks
Interlocked. decrement ( Ref _ Jobcount );
}

/// <Summary>
/// Start timing
/// </Summary>
Public Void Start ()
{
_ Isrunning = 0 ;
_ Timer = New Timer (timeraction, _ state, _ start, _ interval );
}

/// <Summary>
/// End Time
/// </Summary>
Public Void Stop ()
{
_ Timer. Dispose ();
Waitutilfinish ();
_ Timer = Null ;
_ Isrunning = 0 ;
}

/// <Summary>
/// Wait until the execution of the task has been completed
/// </Summary>
Private Void Waitutilfinish ()
{
While (_ Jobcount! = 0 )
{
Thread. Sleep (_ interval );
}
}

// Used to keep task serial when concurrent tasks are not allowed
Private Int _ Isrunning = 0 ;
Private Int _ Jobcount = 0 ;
Private Bool _ Isconcurrent =False ;

Private Timercallback _ Action = Null ;
Private Timer _ timer = Null ;

Private Timespan _ start;
Private Timespan _ interval;
Private Object _ state;
}

Test code:

C #

 1 Fixedratetimer timer = New Fixedratetimer (timespan. fromseconds ( 1 ), Timespan. fromseconds ( 2 ),
2 S =>
3 {
4 Console. writeline ( " Start running: " + Datetime. Now );
5 Thread. Sleep ( 5000 );
6 Console. writeline ( " End running: " + Datetime. Now );
7 }, Null );
8 Timer. Start ();
9 Thread. Sleep (timespan. fromseconds ( 20 ));
10 Timer. Stop ();
11 Console. writeline ( " Try again " );
12 Timer. Start ();
13 Thread. Sleep (timespan. fromseconds ( 20 ));
14 Timer. Stop ();

Running result:

It can be seen that although the task is executed for a long time, it is still executed one by one.
 

2. Constant latency timer (the idle time between tasks is constant ).
Encapsulated fixeddelaytimer class:

C #

     Public   Class Fixeddelaytimer
{
/// <Summary>
/// Constructor
/// </Summary>
/// <Param name = "start"> How long will the execution start after startup delay? </Param>
/// <Param name = "interval"> The time from the end of the next execution. </Param>
/// <Param name = "action"> Task Delegation </Param>
/// <Param name = "state"> Task status parameters </Param>
Public Fixeddelaytimer (timespan start, timespan interval, timercallback action, Object State = Null )
{
_ Action = action;

_ Start = start;
_ Interval = interval;
_ State = State;
}

Private Void Timeraction ( Object S)
{
Thread. Sleep (_ start );
While (_ Isexit = 0 )
{
_ Action (s );
Thread. Sleep (_ interval );
}
}

/// <Summary>
/// Start timing
/// </Summary>
Public Void Start ()
{
_ Isexit = 0 ;
_ Thread = New Thread ( New Parameterizedthreadstart (timeraction ));
_ Thread. Start ();
}

/// <Summary>
/// End Time
/// </Summary>
Public Void Stop ()
{
// Notifies the thread to exit
Interlocked. Exchange ( Ref _ Isexit, 1 );
// Wait until thread execution is completed
_ Thread. Join ();
_ Thread = Null ;
}

Private Int _ Isexit = 0 ; // Whether to exit the timer Loop

Private Timercallback _ Action = Null ;
Private Thread _ thread = Null ;

Private Timespan _ start;
Private Timespan _ interval;
Private Object _ state;
}

Test code:

C #

 1 Fixeddelaytimer timer = New Fixeddelaytimer (timespan. fromseconds (1 ), Timespan. fromseconds ( 2 ),
2 S =>
3 {
4 Console. writeline ( " Start running: " + Datetime. Now );
5 Thread. Sleep ( 5000 );
6 Console. writeline ( " End running: " + Datetime. Now );
7 }, Null );
8 Timer. Start ();
9 Thread. Sleep (timespan. fromseconds ( 20 ));
10 Timer. Stop ();
11 Console. writeline (" Try again " );
12 Timer. Start ();
13 Thread. Sleep (timespan. fromseconds ( 20 ));
14 Timer. Stop ();

Running result: running result:

We can see that the execution time of each task is constant from the start time of the next task to the value we specified.

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.