Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Task.Delay as a timer?

Tags:

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 (?)

like image 909
Sharun Avatar asked Feb 14 '17 07:02

Sharun


People also ask

Does task delay create a new thread?

Task. Delay does not create new Thread, but still may be heavy, and no guaranties on order of execution or being precise about deadlines.

Does task delay block?

Task. Delay() is asynchronous. It doesn't block the current thread.

Does task delay block the thread?

Delay(1000) doesn't block the thread, unlike Task. Delay(1000). Wait() would do, more details.

What does task delay mean?

Task Delay means non-meeting of the preplanned due date of a task.


2 Answers

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(); }  // ... 
like image 197
Fabio Avatar answered Oct 02 '22 05:10

Fabio


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.

like image 31
Enigmativity Avatar answered Oct 02 '22 05:10

Enigmativity