C# 5 and async timers

2019-04-04 14:20发布

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

2条回答
老娘就宠你
2楼-- · 2019-04-04 14:55

Try use

await Task.Delay(500);
查看更多
神经病院院长
3楼-- · 2019-04-04 14:57

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.

查看更多
登录 后发表回答