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)有帮助。 –