c# - 在 c# 中非阻塞等待/延迟一段时间的最佳实现是什么

标签 c# wpf windows-store-apps

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

祝你好运!

[编辑] 我试过这个但没有用。

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

}

最佳答案

参见 Task.Delay

它使用定时器而不是阻塞线程来安排在未来某个时间完成的任务。

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

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

关于c# - 在 c# 中非阻塞等待/延迟一段时间的最佳实现是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20256607/

相关文章:

c# - 有效地更新表的详细信息?

c# - WPF和WinForms Dispatcher应该统一吗?

c# - 创建 GeoJson c#

c# - XmlSerializer 保存空文件

c# - 使用 DocumentViewer 控件呈现 PDF?

windows-store-apps - 将APPX打包在APPXBUNDLE中

c# - Windows 8 Store Apps 中 c# CollectionBase 的替代品是什么?

windows-store-apps - 您的 Microsoft Publisher ID 是否必须保密?

c# - 由于回发而未存储变量

c# - 使用 helix 工具包创建可点击对象