Microsoft說:「異步和await關鍵字不會導致創建額外的線程。異步方法不需要多線程,因爲異步方法不會在其自己的線程上運行。該方法在當前同步上下文上運行,並僅在該方法處於活動狀態時纔在線程上使用時間。您可以使用Task.Run將CPU綁定的工作移動到後臺線程,但後臺線程無助於只等待結果可用的進程。「C#控制流等待異步和線程
以下是Microsoft使用的Web請求示例用於解釋異步和等待的使用。 (https://msdn.microsoft.com/en-us/library/mt674880.aspx)。在問題結尾我粘貼了示例代碼的相關部分。
我的問題是,在每個「var byteArray = await client.GetByteArrayAsync(url);」語句之後,控件返回到CreateMultipleTasksAsync方法,然後調用另一個ProcessURLAsync方法。在三次下載被調用後,它開始等待第一個ProcessURLAsync方法完成。但是如果ProcessURLAsync沒有在單獨的線程中運行,它如何繼續執行DisplayResults方法?因爲如果它不在不同的線程上,在將控制權返回給CreateMultipleTasksAsync之後,它永遠無法完成。你能提供一個簡單的控制流程,以便我能理解嗎?
假設任務download3 = ProcessURLAsync(..)之前完成了第一client.GetByteArrayAsync方法,正是被稱爲第一DisplayResults什麼時候?
private async void startButton_Click(object sender, RoutedEventArgs e)
{
resultsTextBox.Clear();
await CreateMultipleTasksAsync();
resultsTextBox.Text += "\r\n\r\nControl returned to startButton_Click.\r\n";
}
private async Task CreateMultipleTasksAsync()
{
// Declare an HttpClient object, and increase the buffer size. The
// default buffer size is 65,536.
HttpClient client =
new HttpClient() { MaxResponseContentBufferSize = 1000000 };
// Create and start the tasks. As each task finishes, DisplayResults
// displays its length.
Task<int> download1 =
ProcessURLAsync("http://msdn.microsoft.com", client);
Task<int> download2 =
ProcessURLAsync("http://msdn.microsoft.com/en-us/library/hh156528(VS.110).aspx", client);
Task<int> download3 =
ProcessURLAsync("http://msdn.microsoft.com/en-us/library/67w7t67f.aspx", client);
// Await each task.
int length1 = await download1;
int length2 = await download2;
int length3 = await download3;
int total = length1 + length2 + length3;
// Display the total count for the downloaded websites.
resultsTextBox.Text +=
string.Format("\r\n\r\nTotal bytes returned: {0}\r\n", total);
}
async Task<int> ProcessURLAsync(string url, HttpClient client)
{
var byteArray = await client.GetByteArrayAsync(url);
DisplayResults(url, byteArray);
return byteArray.Length;
}
private void DisplayResults(string url, byte[] content)
{
// Display the length of each website. The string format
// is designed to be used with a monospaced font, such as
// Lucida Console or Global Monospace.
var bytes = content.Length;
// Strip off the "http://".
var displayURL = url.Replace("http://", "");
resultsTextBox.Text += string.Format("\n{0,-58} {1,8}", displayURL, bytes);
}
}
我想想你可能會發現我的['async' intro](http://blog.stephencleary.com/2012/02/async-and-await.html)有幫助。 –