Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delay an action execution when use Task

Tags:

c#

I have the following code:

Action<CancellationToken> act1 = tk1 => {
   //sleep for 5 seconds
   Console.WriteLine(...);
};

Task t1 = new Task(() => execute(act1));

t1.Start();

How to sleep inside action ? I tried with :

Thread.Sleep(TimeSpan.FromSeconds(5));

and

Task.Delay(TimeSpan.FromSeconds(5));
like image 870
Snake Eyes Avatar asked Nov 01 '25 09:11

Snake Eyes


1 Answers

With

Task.Delay(TimeSpan.FromSeconds(5));

a new Task is created that is ran asynchronally by default. Hence your method will continue running independently from the Task. You have several option to synchronize to your Task.

If you are in an async method you can await the Task

await Task.Delay(TimeSpan.FromSeconds(5));

otherwise, you may always use Task.Wait

Task.Delay(TimeSpan.FromSeconds(5)).Wait();

this will block the method until the Task has finished running.

In your case you can make your Lambda async

Action<CancellationToken> act1 = async tk1 => {
   await Task.Delay(TimeSpan.FromSeconds(5), tk1);
   Console.WriteLine(...);
};
like image 50
Paul Kertscher Avatar answered Nov 02 '25 23:11

Paul Kertscher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!