gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 03:08:38 24 4
gpt4 key购买 nike

我在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com