以下是Microsoft用于解释异步和await的网络请求示例 (https://msdn.microsoft.com/en-us/library/mt674880.aspx)。我在问题末尾粘贴了示例代码的相关部分。
我的问题是,在每个“var byteArray = await client.GetByteArrayAsync(url);”语句之后,控制返回CreateMultipleTasksAsync方法,然后调用另一个ProcessURLAsync方法。在调用三个下载之后,它开始等待第一个ProcessURLAsync方法完成。但是如果ProcessURLAsync不在单独的线程上运行,它如何继续进行DisplayResults方法呢?因为如果它不在不同的线程上,将控制返回给CreateMultipleTasksAsync后,它永远无法完成。你能提供一个简单的控制流程让我理解吗?
假设在Task 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
介绍很有帮助。 - Stephen Cleary