A workaround for the re-entry of timer timers in C #

Source: Internet
Author: User
Tags net thread

The timer is used in the project. As the service is started as a timed task, the relevant operation is timed to the specified time, but I want it to be executed only once during the specified time, to avoid the problem of re-entry.

First of all, a brief introduction to the timer, which is referred to as the timer refers to the System.Timers.timer, as the name implies, can be at the specified interval is the event raised. The official introduction here, excerpt as follows:

The timer component is a server-based timer that enables you to specify the periodic interval at which the Elapsed event is raised in the application. You can then provide general processing by handling this event. For example, suppose you have a critical server that must remain operational 24 hours a day, 7 days a week. You can create a service that uses a Timer to periodically check the server and ensure that the system is turned on and running. If the system does not respond, the service can attempt to restart the server or notify the administrator.    Server-based Timer is designed for use with worker threads in a multithreaded environment. Server timers can move between threads to handle the Elapsed event that is raised, which can cause events to be raised more accurately on time than the Windows timer.

What's the advantage of using this timer? Mainly because it is implemented through the. NET Thread pool, lightweight, accurate timing, no special requirements for applications and messages.

How the timer is used has been written before: use of C # System.Timers.Timer timers and automatic cleanup of memory applications at timed intervals

What do you mean, re-entry? This is a concept about multithreaded programming: In a program, when multiple threads are running concurrently, it is possible that the same method is being called simultaneously by multiple processes. When there are some non-thread-safe code in this method, the method re-entry causes inconsistent data. Timer method re-entry refers to the use of multi-threaded timers, a timer processing is not completed, to the time, another timer will continue to enter the method for processing.

the workaround for the re-entry problem of the timer is as follows :

1, use lock Lock (Object) method to prevent re-entry, indicating that a timer processing is executing, the next timer occurs when the last one is not completed to wait for execution , the application of re-entry rarely occurs. Add lock to the triggering method so that when thread 2 enters the triggering method, the discovery has been locked and waits for the code in the lock to finish executing, the code is as follows:

 Private StaticSystem.Timers.Timer Atimer =NewSystem.Timers.Timer ();Private Static ObjectLoker=New Object(); /// <summary>        ///Set Timer/// </summary>         Public Static voidSetTimer () {//Read Configuration Time            Try{atimer.interval=30000; Atimer.elapsed+=NewSystem.Timers.ElapsedEventHandler (ontimedevent); Atimer.autoreset=true;//each time the elapsed event is triggered by the time it is specifiedatimer.enabled =true;//Indicates whether the Timer should raise the Elapsed event.             }            Catch(Exception ex) {Logmanager.recordlog (Logtype.error,"ipad Data sync error:"+Ex.            MESSAGE,EX); }        }        Private Static voidontimedevent (Object source, Elapsedeventargs e) {//If the current time is configured for on-time, come in            varTime =convert.toint32 (SynchronousHelper.AppConfig.get_Items ("Syctime")); if(DateTime.Now.Hour = = Time && DateTime.Now.Minute = =0)            {                //Lock so that when thread 2 enters the triggering method, it finds that it has been locked and waits for the code in the lock to finish executing                Lock(Loker) {Logmanager.recordlog (Logtype.info,"Data start sync time:"+ E.signaltime,NULL);                    Settimerstart (); System.Threading.Thread.Sleep (60000);//run over the current minute, so that only one time can come in the hour                }            }        }

2. Set a flag, indicating that a timer processing is executing, the next timer occurs when the last one did not finish to give up (notice here is giving up, rather than waiting for Oh, see what the execution result is understood) execution, applicable to re-enter the scene often occurs. In the multi-threaded Intimer assignment is not secure enough, Interlocked.exchange provides a lightweight thread-safe way to assign objects (feeling higher than the larger, is a more recommended method).

 Private StaticSystem.Timers.Timer Atimer =NewSystem.Timers.Timer ();Private Static intIntimer =0; /// <summary>        ///Set Timer/// </summary>         Public Static voidSetTimer () {//Read Configuration Time            Try{atimer.interval=30000;//half-minute trigger once atimer.elapsed+=NewSystem.Timers.ElapsedEventHandler (ontimedevent); Atimer.autoreset=true;//each time the elapsed event is triggered by the time it is specifiedatimer.enabled =true;//Indicates whether the Timer should raise the Elapsed event.             }            Catch(Exception ex) {Logmanager.recordlog (Logtype.error,"ipad Data sync error:"+Ex.            MESSAGE,EX); }        }        Private Static voidontimedevent (Object source, Elapsedeventargs e) {//If the current time is configured for on-time, come in            varTime =convert.toint32 (SynchronousHelper.AppConfig.get_Items ("Syctime")); if(DateTime.Now.Hour = = Time && DateTime.Now.Minute = =0)            {                //Intimer Sets a flag that indicates that a timer handler is executing, and when the next timer occurs, it is abandoned when the last one is not executed.                if(Interlocked.exchange (refIntimer,1) ==0) {Logmanager.recordlog (Logtype.info,"Data start sync time:"+ E.signaltime,NULL);                    Settimerstart (); System.Threading.Thread.Sleep (60000);//execution waits over the current minute so that only one can come in once in the hourInterlocked.exchange (refIntimer,0); }            }        }

A little summary, the timer is a very simple use of the class, take it, here is the main summary of the use of the timer to re-enter the problem of the solution, have not thought about this problem, the solution is quite simple. The solution here also applies multi-threaded re-entry issues.

A workaround for the re-entry of timer timers in C #

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.