c# - async with await 与同步调用有何不同?

标签 c# .net asynchronous async-await c#-5.0

我在 Asynchronous Programming with Async and Await 上阅读有关异步函数调用的内容.

在第一个例子中,他们这样做,我得到:

Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");

// You can do work here that doesn't rely on the string from GetStringAsync.
DoIndependentWork();

string urlContents = await getStringTask;

但随后他们解释说,如果在此期间没有任何工作要做,您可以这样做:

string urlContents = await client.GetStringAsync();

据我了解,await 关键字将暂停代码流,直到函数返回。那么这与下面的同步调用有何不同?

string urlContents = client.GetString();

最佳答案

调用 await client.GetStringAsync() 会将执行交给调用方法,这意味着它不会等待方法完成执行,因此不会阻塞线程。一旦它在后台执行完毕,该方法将从它停止的地方继续。

如果您只是调用client.GetString(),线程将不会继续执行,直到该方法执行完毕,这将阻塞线程并可能导致UI 无响应。

例子:

public void MainFunc()
{
    InnerFunc();
    Console.WriteLine("InnerFunc finished");
}

public async Task InnerFunc()
{
    // This causes InnerFunc to return execution to MainFunc,
    // which will display "InnerFunc finished" immediately.
    string urlContents = await client.GetStringAsync();

    // Do stuff with urlContents
}

public void InnerFunc()
{
    // "InnerFunc finished" will only be displayed when InnerFunc returns,
    // which may take a while since GetString is a costly call.
    string urlContents = client.GetString();

    // Do stuff with urlContents
}

关于c# - async with await 与同步调用有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17250047/

相关文章:

c# - 使用 Process、RegistryKey 将 .NET Framework 代码移植到 .NET Standard

jquery - 如何在 ASP.NET MVC 中保留表单的异步上传文件?

php - 使用 php 创建异步数据库

c# - Twitterizer- 远程服务器返回错误 : (401) Unauthorized

c# - C# 中的静态抽象方法(特定用例的替代方法)

c# - 在 wpf 中用 < 字符重命名按钮

c# - 如何防止工具提示在自定义控件中闪烁?

c# - 下载文件超时

javascript - Node.js 中的变量未异步更新

c# - 在 WPF 中理解和创建事件时遇到问题