2016-11-26 101 views
-3

我已經閱讀了至少十幾篇文章,我想我終於明白了。批評我的以下解釋。我對異步等待的理解是否正確?

如果我使用async關鍵字在函數內部,它標誌着的功能的調用者,當它到達await關鍵字功能裏面那麼就可以繼續前進,之後做任何獨立工作函數調用,直到await ed函數的結果被返回,然後它可以從其停止的地方返回結束。

+1

簡單的回答這個問題「是」。除此之外的任何東西都是無關緊要的。 – Enigmativity

回答

2

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與否。異步簡單地指示編譯器:

  1. 的方法將被調用async,並需要變成一個狀態機和
  2. 當寫return a(其中aint),將結果包裝成Task<int>
2

「異步」改性劑被用在方法聲明/簽名指示(編譯器),該方法米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操作。

編譯器會以您的名義生成代碼,以便所有這些都可以工作。

「異步/等待」的另一個好處是關於代碼可讀性(線性流,異步代碼讀取,如同步)和異常處理,大部分時間。

This article shows the many ways asynchronous operations can be accomplished (with and without "async/await")

而且請記住,「異步/等待」已經很少做多線程。它旨在幫助實現非阻塞操作(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-blockingwhich links to this nice SO post

And this one is a FAQ on async/await.

+0

「換句話說,它表明方法本身可以等待。」這是一個常見的誤解,但是必須正確:你不*等待方法,你只等待任務!在許多情況下,您在等待不是通過異步方法創建的任務。 – Voo

+0

刪除了有問題的句子,但要清楚,「await」關鍵字只能用於標有「async」修飾符的方法內。 – Klinger