Fulproof Fulproof - 1 year ago 143
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 Source

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) =>
    timer.Interval = milliseconds;
    timer.AutoReset = false;
    return tcs.Task;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download