我已經閱讀了至少十幾篇文章,我想我終於明白了。批評我的以下解釋。我對異步等待的理解是否正確?
如果我使用async
關鍵字在函數內部,它標誌着的功能的調用者,當它到達await
關鍵字功能裏面那麼就可以繼續前進,之後做任何獨立工作函數調用,直到await
ed函數的結果被返回,然後它可以從其停止的地方返回結束。
我已經閱讀了至少十幾篇文章,我想我終於明白了。批評我的以下解釋。我對異步等待的理解是否正確?
如果我使用async
關鍵字在函數內部,它標誌着的功能的調用者,當它到達await
關鍵字功能裏面那麼就可以繼續前進,之後做任何獨立工作函數調用,直到await
ed函數的結果被返回,然後它可以從其停止的地方返回結束。
async
關鍵字在等待方面不影響被調用方中的任何內容。無論它來自哪裏,都可以等待任何Task
。讓我們來看看下面這個例子:
async Task Main()
{
Console.WriteLine("Starting A now.");
GetResult();
Console.WriteLine("Finished A now.");
Console.WriteLine("Starting B now.");
await GetResult();
Console.WriteLine("Finished B now.");
Console.WriteLine("Starting C now.");
GetResultAync();
Console.WriteLine("Finished C now.");
Console.WriteLine("Starting D now.");
await GetResultAync();
Console.WriteLine("Finished D now.");
}
Task GetResult()
{
return Task.Delay(5000).ContinueWith(a => Console.WriteLine("Finished!"));
}
async Task GetResultAync()
{
await Task.Delay(5000).ContinueWith(a => Console.WriteLine("Finished!"));
}
正如你所看到的 - Main
能夠等待結果無論的方法是async
與否。異步簡單地指示編譯器:
async
,並需要變成一個狀態機和return a
(其中a
爲int
),將結果包裝成Task<int>
「異步」改性劑被用在方法聲明/簽名指示(編譯器),該方法米ight使用「await」調用一個或多個異步操作。 「async」可以在方法內使用「await」。 「異步」修飾符不是在方法內部使用,它用於方法簽名,如「public」和「private」關鍵字。
是這樣的:(example taken from here:)
public async Task<int> AccessTheWebAsync() { ... }
可以調用上述的方法如下:
Task<int> accessWebTask = AccessTheWebAsync();
... --> code that does not depend on the result of the previous line
var result = await accessWebTask;
... --> code that should not execute until the operation above is done
or shorter form:
10 var result = await AccessTheWebAsync();
11 ... code after awaited operation
的「等待」運算符表示一個懸掛點,這是說,代碼在等待的操作需要等待操作(第10行)完成之後才能執行其餘代碼(第11行等)。 「await」可以用於void返回方法,在這種情況下,沒有等待,這是一個fire and forget操作。
編譯器會以您的名義生成代碼,以便所有這些都可以工作。
「異步/等待」的另一個好處是關於代碼可讀性(線性流,異步代碼讀取,如同步)和異常處理,大部分時間。
而且請記住,「異步/等待」已經很少做多線程。它旨在幫助實現非阻塞操作(db/file system/network)和UI響應。 This SO post is a good read./This series is worth reading also.
And so is this MS article (Synchronous and Asynchronous I/O).
如果你有興趣在一個更示意圖藉此文章一看: The difference between asynchronous and non-blocking (which links to this nice SO post)
簡單的回答這個問題「是」。除此之外的任何東西都是無關緊要的。 – Enigmativity