What's the best implemention for non-blocking wait/delay for a period of time in c#

好久不见. 提交于 2020-06-23 12:17:01

问题


Currently I need to implement a simple non-blocking delay function in a Windows Store app project. This function should do nothing, just idle for a specific period of time without blocking the UI. My question is: how to implement such a function properly? I know this is an old question, but I really have no clue after some search online.

Best wishes!

[Edit] I've tried this but not work.

public static async Task WaitFor(int millisecondsDelay)
{
    var idleTask = Task.Run(() => { Task.Delay(millisecondsDelay); });
    await Task.WhenAny(new Task[] { idleTask });

}

回答1:


See Task.Delay

It schedules a task that completes at a future time using timer rather than blocking a thread.

An example that waits 5 seconds and then continues:

private async Task DelayThenDoSomeWork()
{
    await Task.Delay(5000);
    // Do something
    var dialog = new MessageDialog("Waiting completed.");
    await dialog.ShowAsync();
}


来源:https://stackoverflow.com/questions/20256607/whats-the-best-implemention-for-non-blocking-wait-delay-for-a-period-of-time-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!