c# - UI 线程中 Task.Wait 的替代方法

标签 c# windows-8 microsoft-metro task-parallel-library async-ctp

我知道在 UI 线程中调用 Task.Wait 是不好的。它会导致死锁。请引用

Constructor invoke async method

Await, and UI, and deadlocks! Oh my!

采用以下代码:

    public MainPage()
    {
        this.InitializeComponent();

        step0();
        step1();
    }

    private async Task step0()
    {
        await Task.Delay(5000);
        System.Diagnostics.Debug.WriteLine("step 0");
    }

    private async Task step1()
    {
        await Task.Delay(3000);
        System.Diagnostics.Debug.WriteLine("step 1");
    }
}

如何确保“第 0 步”始终在“第 1 步”之前打印?使用 Task.Wait 会导致死锁。 这是 Windows 应用商店应用

最佳答案

您可以使用 Task.ContinueWith 将任务链接在一起,以便它们按顺序发生。

public MainPage()
{
    this.InitializeComponent();

    step0().ContinueWith(t => step1());
}

此外,Alexei 的评论是正确的。 Task.Wait阻塞 UI 线程。死锁是另外一回事。

关于c# - UI 线程中 Task.Wait 的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13411339/

相关文章:

c# - WinRT 许可

javascript - 此版本的应用程序不支持错误 : Cannot open be opened because its project type(. jsproj) - 适用于 Windows 8 的 VS Express RC 2012

c# - 如何保存复选框的状态

c++ - C++ 中的 _In_ 是什么?

c# - ConcurrentQueue 与 Queue + 锁的性能对比

c# - 如何真正快速地选择列表框中的所有项目?

javascript - 使用 JS 计算所有已检查行的字段总和

c# - 比较具有相同内容的 XLSX 文件之间的 MD5 哈希值

c# - Windows 8 App Webview 提取 cookie

c# - Metro 应用程序中的键盘快捷键