C# 5 and async timers

2019-04-04 14:27发布

问题:

Is there a new Timer API somewhere that allows me to do this?

await timer.wait(500);

Basically, to sleep for X ms and then resume execution of the rest of a function

回答1:

Try use

await Task.Delay(500);


回答2:

I have a helper that I really like, just to add a bit of readability:

public static Task Seconds(this int seconds)
{
    return Task.Delay(new TimeSpan(0,0,seconds));
}

This allows me to use something like

await 5.Seconds();

You could easily make similar extension methods for milliseconds, minutes, hours, or whatever.