I want to execute some code on each second. The code I am using now is:
Task.Run((Action)ExecuteSomething);
And ExecuteSomething()
is defined as below:
private void ExecuteSomething() { Task.Delay(1000).ContinueWith( t => { //Do something. ExecuteSomething(); }); }
Does this method block a thread? Or should I use Timer
class in C#? And it seems Timer also dedicates a separate thread for execution (?)
Task. Delay does not create new Thread, but still may be heavy, and no guaranties on order of execution or being precise about deadlines.
Task. Delay() is asynchronous. It doesn't block the current thread.
Delay(1000) doesn't block the thread, unlike Task. Delay(1000). Wait() would do, more details.
Task Delay means non-meeting of the preplanned due date of a task.
Task.Delay
uses Timer
internally
With Task.Delay
you can make your code a little-bid clearer than with Timer
. And using async-await
will not block the current thread (UI usually).
public async Task ExecuteEverySecond(Action execute) { while(true) { execute(); await Task.Delay(1000); } }
From source code: Task.Delay
// on line 5893 // ... and create our timer and make sure that it stays rooted. if (millisecondsDelay != Timeout.Infinite) // no need to create the timer if it's an infinite timeout { promise.Timer = new Timer(state => ((DelayPromise)state).Complete(), promise, millisecondsDelay, Timeout.Infinite); promise.Timer.KeepRootedWhileScheduled(); } // ...
Microsoft's Reactive Framework is ideal for this. Just NuGet "System.Reactive" to get the bits. Then you can do this:
IDisposable subscription = Observable .Interval(TimeSpan.FromSeconds(1.0)) .Subscribe(x => execute());
When you want to stop the subscription just call subscription.Dispose()
. On top of this the Reactive Framework can offer far more power than Tasks or basic Timers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With