How to put a task to sleep (or delay) in C# 4.0?
Use the Microsoft.Bcl.Async package from NuGet, it has TaskEx.Delay
.
You can use a Timer
to create a Delay
method in 4.0:
public static Task Delay(double milliseconds)
{
var tcs = new TaskCompletionSource<bool>();
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed+=(obj, args) =>
{
tcs.TrySetResult(true);
};
timer.Interval = milliseconds;
timer.AutoReset = false;
timer.Start();
return tcs.Task;
}
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main()
{
Delay(2000).ContinueWith(_ => Console.WriteLine("Done"));
Console.Read();
}
static Task Delay(int milliseconds)
{
var tcs = new TaskCompletionSource<object>();
new Timer(_ => tcs.SetResult(null)).Change(milliseconds, -1);
return tcs.Task;
}
}
From the section How to implement Task.Delay in 4.0