Several Methods for executing a function repeatedly at a certain interval.

Source: Internet
Author: User

Several Methods for executing a function repeatedly at a certain interval.

If there is an operation, we need to do it later, or do it every other time. There are many ways to do this.

Independent thread

Yes, only programmers who have a thorough understanding of the. NET Framework can use this solution. However, in reality, this solution is not uncommon.

        public static void Repeat(this Action action, TimeSpan interval)        {            new Thread(new ThreadStart(() =>            {                while(true)                {                    Thread.Sleep(interval);                    action();                }            })).Start();        }

This method has another advantage over other methods: it ensures that action is called by only one thread. If this action is not used elsewhere, action is thread-safe.

Timer class

There are 4 Timer classes in. Net Framework. Joe Albahari makes a full comparative analysis of the four timers in his Threading in C. I will not go into details.

However, the shortcomings of the Timer class are also obvious.

L non-thread security. Except for the two Timer classes used in the UI, other Timer classes do not guarantee that they are always executed by the same thread. Of course, this multi-threaded execution method ensures the efficiency and the Time Precision of triggering events.

L operation backlog. If a Timer is triggered once in 500 ms, ms is executed each time. As you can imagine, the action you want to perform is essentially executed in this way:

While (true)

Action ();

If it is a multi-threaded Timer, the situation will be worse. Your action will be executed by multiple threads at the same time. In most cases, we do not want things to look like this. However, it is a pity that the Timer class does not care about how long your EventHandler executes. It just finds a thread to execute your action once, no matter whether the last action has been completed.

L inconvenient to use. Think about what we want to do: "delay or scheduled execution of a function .", Let's take a look at the code to be written. I think it is too complicated than the operation to be done.

Timer timer = new Timer (1000); timer. elapsed + = (sender, e) => action (); timer. start (); // timer when not required. dispose ();

Think about how much code to write if you want to ensure thread security and avoid Operation backlog? Therefore, Quartz. NET was born to simplify the code for such scheduled operations.

Reactive Extension

This can be simplified:

Observable. Interval (interval). Subscribe (I => action ());

The behavior of the above Code is the same as that of the Timer class, and there is a backlog of operations. There are many solutions. Here is a simple example.

        public static void Repeat(this Action action, TimeSpan interval)        {            Observable.Defer(action.ToAsync())                      .DelaySubscription(interval)                      .Repeat().Subscribe();        }

The preceding method ensures the interval between each action execution. So there will be no action backlog 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.