Solution to the problem of Timer timer re-entry 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 static System.Timers.Timer Atimer = new System.Timers.Timer ();   Private static Object Loker=new object ();            <summary>///Set Timer///</summary> public static void SetTimer () {                Read config time try {atimer.interval = 30000;                atimer.elapsed + = new System.Timers.ElapsedEventHandler (ontimedevent); Atimer.autoreset = true;//Each to a specified time elapsed event is triggered to the time atimer.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 void Ontimedevent (Object source, Elapsedeventargs e) {//If the current time is for a configured punctuality            In the room var time =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 processing in the execution lock (loker) {Logmanager .                    Recordlog (Logtype.info, "Data Start sync Time:" + e.signaltime, NULL);                    Settimerstart (); System.Threading.Thread.Sleep (60000); Run past the current minute so that only one time can be entered in the Hour}}}

2. Place a flag that indicates that a timer handler is executing, and the next timer occurs when the previous one does not complete abort (Note that this is a waiver, not a wait oh, see how the execution result is understood) execution, Suitable for re-entry of frequently occurring scenarios. 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 static System.Timers.Timer Atimer = new System.Timers.Timer ();        private static int intimer = 0;            <summary>///Set Timer///</summary> public static void SetTimer () { Read config time try {atimer.interval = 30000;//half minute trigger once atimer.elapsed + = NE                W System.Timers.ElapsedEventHandler (ontimedevent); Atimer.autoreset = true;//Each to a specified time elapsed event is triggered to the time atimer.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 void Ontimedevent (Object source, Elapsedeventargs e) {//If the current time is for a configured punctuality            In the room var time =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 found that the last one has not been executed and discards if (Interlocked.exchange (ref intimer, 1                    ) = = 0) {Logmanager.recordlog (logtype.info, "Data Start sync Time:" + e.signaltime, NULL);                    Settimerstart (); System.Threading.Thread.Sleep (60000);                The execution waits over the current minute, so that the whole point can only come in once Interlocked.exchange (ref intimer, 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 when the problem of re-entry, not previously thought of this problem, the solution is quite simple. The solution here also applies multi-threaded re-entry issues.

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.