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.