Fulproof Fulproof - 1 month ago 21
C# Question

How to put a task to sleep (or delay) in C# 4.0?

There is Task.Delay in .NET 4.5

How can I do the same in .NET 4.0?

Answer

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;
}
Comments