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));
                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(...);
};
                        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