【问题标题】:Should I await async calls like MessageDialog and Launcher methods?我应该等待像 MessageDialog 和 Launcher 方法这样的异步调用吗?
【发布时间】:2012-11-03 10:59:20
【问题描述】:

Visual Studio 给了我各种警告,告诉我不要等待我的 MessageDialog.ShowAsync()Launcher.LaunchUriAsync() 方法。

上面写着:

“考虑应用 await 关键字”

显然我不需要等待他们,但这对他们有好处吗?

等待调用显然阻塞了不好的 UI 线程 - 那么为什么 Visual Studio 会抛出这么多警告呢?

【问题讨论】:

标签: c# asynchronous windows-8 windows-runtime async-await


【解决方案1】:

等待调用显然阻塞了不好的 UI 线程

await 实际上并没有阻止 UI。 await 暂停该方法的执行,直到等待的任务完成,然后继续该方法的其余部分。阅读有关await (C# Reference) 的更多信息。

显然我不需要等待他们,但这对他们有好处吗?

如果不使用await,那么调用MessageDialog.ShowAsync()的方法可能会在MessageDialog.ShowAsync()完成之前完成。您不需要这样做,但这是一种很好的做法。

例如,假设你想下载一个字符串并使用它,而不用等待:

async void MyAsyncMethod()
{
    var client = new HttpClient();
    var task = client.GetStringAsync("http://someurl.com/someAction");

    // Here, GetStringAsync() may not be finished when getting the result
    // and it will block the UI thread until GetStringAsync() is completed.
    string result = task.Result;
    textBox1.Text = result; 
}

但是如果我们使用await:

async void MyAsyncMethod()
{
    var client = new HttpClient();
    string result = await client.GetStringAsync("http://someurl.com/someAction");

    // This method will be suspended at the await operator, 
    // awaiting GetStringAsync() to be completed,
    // without freezing the UI, and then continues this method.

    textBox1.Text = result;
}

【讨论】:

  • 该方法的第一个版本会阻塞调用/UI 线程,直到您访问 Result 属性时任务完成。
  • @JamesManning 你是对的,我在想什么。我更新了 cmets。下次我会做一个更好的例子=)感谢您指出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-27
  • 2015-11-09
  • 2016-02-23
相关资源
最近更新 更多