How to solve the re-entry problem of Timer in C,

Source: Internet
Author: User
Tags net thread

How to solve the re-entry problem of Timer in C,

In the project, a timer is used as a scheduled task when the service starts, and related operations are scheduled according to the specified on-time. However, I only want to execute the timer once within the specified on-time, to avoid re-entry problems.

Timer refers to System. Timers. timer, as its name implies, that is, events can be triggered at specified intervals. The official introduction here is excerpted as follows:

The Timer component is a server-based Timer that enables you to specify the periodic interval at which Elapsed events are triggered in an application. You can then process this event to provide regular processing. For example, assume that you have a critical server that must be running 24 hours a day, 7 days a week. You can create a service that uses Timer to regularly check the server and ensure that the system is enabled and running. If the system does not respond, the service can restart the server or notify the administrator. Server-based Timer is designed for auxiliary threads in multi-threaded environments. The server timer can be moved between threads to process the triggered Elapsed event, so that the event can be triggered more accurately than the Windows timer.

So what are the advantages of using this timer? This is mainly because it is implemented through the. NET Thread Pool, lightweight, accurate timing, and has no special requirements on applications and messages.

How is Timer used? I wrote this article before: C # System. Timers. Timer usage and timed Automatic Cleaning of Memory Applications.

What is re-import?? This is a concept related to multi-threaded programming: when multiple threads run simultaneously in a program, the same method may be called by multiple processes at the same time. When some non-thread-safe code exists in this method, method re-entry may result in data inconsistency. Timer method re-import refers to the use of multi-thread Timer, a Timer processing has not been completed, by the time, the other Timer will continue to enter this method for processing.

Try the following to solve the re-entry problem of the Timer::

1. Use the lock (Object) method to prevent re-entry, indicating that a Timer is being processed. When the next Timer occurs, it is found that the previous one is not completed.Waiting for executionApplicable to scenarios with rare re-entry. Add lock to the trigger method. In this way, when thread 2 enters the trigger method, it finds that it has been locked and will wait until the code in the lock is completed and is being executed. The Code is as follows:

Private static System. timers. timer aTimer = new System. timers. timer (); private static object loker = new object (); // <summary> // set the Timer /// </summary> public static void SetTimer () {// read configuration time try {aTimer. interval = 30000; aTimer. elapsed + = new System. timers. elapsedEventHandler (OnTimedEvent); aTimer. autoReset = true; // The aTimer is triggered every time the Elapsed event is triggered. enabled = true; // indicates whether the Timer should trigger the Elapsed event.} Catch (Exception ex) {LogManager. recordLog (LogType. error, "ipad data synchronization Error:" + ex. message, ex) ;}} private static void OnTimedEvent (Object source, ElapsedEventArgs e) {// if the current time is the configured on-time, var time = Convert. toInt32 (SynchronousHelper. appConfig. get_Items ("SycTime"); if (DateTime. now. hour = time & DateTime. now. minute = 0) {// lock, so when thread 2 enters the trigger method, it finds that it has been locked and will wait until the code in the lock is processed and the lock (loker) is executed) {LogManager. recordLog (LogType. info, "Data Synchronization start time:" + e. signalTime, null); SetTimerStart (); System. threading. thread. sleep (60000); // after the execution is completed, the current minute is exceeded, so that only one time can be entered in the hour }}}

2. Set a flag to indicate that a Timer processing is in progress. When the next Timer occurs, it is found that the previous one is not complete.Give up(Note that this is to give up, rather than waiting. You can see the execution result to understand what it means.) The execution is applicable to frequent re-entry scenarios. It is not safe to assign a value to inTimer under multiple threads, Interlocked. exchange provides a lightweight thread-safe method for assigning values to objects (it feels high and recommended ).

Private static System. timers. timer aTimer = new System. timers. timer (); private static int inTimer = 0; // <summary> // set the Timer /// </summary> public static void SetTimer () {// read configuration time try {aTimer. interval = 30000; // trigger aTimer once every half minute. elapsed + = new System. timers. elapsedEventHandler (OnTimedEvent); aTimer. autoReset = true; // The aTimer is triggered every time the Elapsed event is triggered. enabled = true; // indicates whether the Timer should trigger the Elapsed event.} Catch (Exception ex) {LogManager. recordLog (LogType. error, "ipad data synchronization Error:" + ex. message, ex) ;}} private static void OnTimedEvent (Object source, ElapsedEventArgs e) {// if the current time is the configured on-time, var time = Convert. toInt32 (SynchronousHelper. appConfig. get_Items ("SycTime"); if (DateTime. now. hour = time & DateTime. now. minute = 0) {// inTimer sets a flag, indicating that a Timer processing is in progress. When the next Timer occurs, if (Interlocked. exchange (ref inTimer, 1) = 0) {LogManager. recordLog (LogType. info, "Data Synchronization start time:" + e. signalTime, null); SetTimerStart (); System. threading. thread. sleep (60000); // wait until the current minute, so that only one Interlocked can be entered in the entire point. exchange (ref inTimer, 0 );}}}

To sum up, timer is a simple class that can be used out of the box. Here we mainly summarize the solution to the re-entry problem when timer is used. I have never thought about this problem before, the solution is also quite simple. The solution here also applies to the multi-thread reconnection problem.

 

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.