c#中一段时间​​非阻塞等待/延迟的最佳实现是什么 [英] What's the best implemention for non-blocking wait/delay for a period of time in c#

查看:53
本文介绍了c#中一段时间​​非阻塞等待/延迟的最佳实现是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我需要在 Windows Store 应用项目中实现一个简单的非阻塞延迟功能.这个函数应该什么都不做,只是空闲一段时间而不阻塞 UI.我的问题是:如何正确实现这样的功能?我知道这是一个老问题,但在网上搜索后我真的不知道.

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.

最好的祝福!

我试过了,但没有用.

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

}

推荐答案

参见 Task.Delay

它使用计时器而不是阻塞线程来安排在未来时间完成的任务.

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

等待 5 秒然后继续的示例:

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();
}

这篇关于c#中一段时间​​非阻塞等待/延迟的最佳实现是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆