2 回答

TA貢獻1773條經驗 獲得超3個贊
鑒于功能:
async Task<int> AccessTheWebAsync()
{
// You need to add a reference to System.Net.Http to declare client.
using (HttpClient client = new HttpClient())
{
Task<string> getStringTask = client.GetStringAsync("https://learn.microsoft.com");
DoIndependentWork();
string urlContents = await getStringTask;
return urlContents.Length;
}
}
當執行到
string urlContents = await getStringTask;
執行可以做兩件事之一:
如果 GetStringAsync() 已經完成,則繼續執行下一行(return urlContents.Length;)
如果 GetStringAsync() 尚未完成,則 AccessTheWebAsync() 的執行將暫停并返回到調用函數,直到 GetStringAsync() 完成。您詢問的段落說明如果我們無論如何都暫停了 AccessTheWebAsync() 的執行,那么暫停然后返回到 AccessTheWebAsync 的費用將被浪費。 因此這不會發生,因為它足夠聰明,知道什么時候暫停執行,什么時候不暫停執行。

TA貢獻2019條經驗 獲得超9個贊
C# 中的異步方法必須始終返回一個任務,如下所示:
public async Task method();
public async Task<bool> asyncMethod();
當它不返回任何東西時,void 就返回Task,在任何其他情況下Task<returntype>
當你調用異步方法時,你可以做三件事:
// Result is now of type Task<object> and will run async with any code beyond this line.
// So using result in the code might result in it still being null or false.
var result = asyncMethod();
// Result is now type object, and any code below this line will wait for this to be executed.
// However the method that contains this code, must now also be async.
var result = await asyncMethod();
// Result is now type Task<object>, but result is bool, any code below this line will wait.
// The method with this code does not require to be async.
var result = asyncMethod().Result;
所以來回答你的問題。
考慮執行代碼的結果是否在代碼的其他地方使用,因為如果你不等待它,結果將被浪費,因為它仍然是 null。
反之亦然,當等待一個不會返回任何東西的方法時,通常不需要等待。
- 2 回答
- 0 關注
- 110 瀏覽
添加回答
舉報