如何:使用 Task.WhenAll 扩展异步演练(C# 和 Visual Basic)
您可以使用 Task.WhenAll 方法提高演练:使用 Async 和 Await 访问 Web(C# 和 Visual Basic)中的异步解决方案的性能。 此方法异步等待多个异步操作,这些异步操作表示为任务集合。
您可能已在本演练中注意到网站下载速度有所差异。 有时,某个网站非常慢,延迟所有剩余下载。 当您运行在本演练中生成的异步解决方案时,如果您不想等待,则可以轻松地终止程序,但更好的选择是同时启动所有下载并让更快的下载继续,不必等待延迟的那些。
您可以将 Task.WhenAll 方法应用于任务集合。 WhenAll 的应用程序会返回直至集合中的每个任务完成时才完成的单个任务。 该任务显示并行运行,但未创建其他线程。 这些任务可以任意顺序完成。
重要
下面的过程介绍对 演练:使用 Async 和 Await 访问 Web(C# 和 Visual Basic) 中开发的异步应用程序的扩展。您可以通过完成此演练或从开发人员代码示例下载代码来开发应用程序。
要运行此示例,必须在你的计算机上安装 Visual Studio 2012、Visual Studio 2013、Visual Studio Express 2012 for Windows Desktop、Visual Studio Express 2013 for Windows 或 .NET Framework 4.5 或 4.5.1。
向您的 GetURLContentsAsync 解决方案中添加 Task.WhenAll
添加 ProcessURLAsync 方法到在 演练:使用 Async 和 Await 访问 Web(C# 和 Visual Basic) 中开发的第一个应用程序。
如果您已从 Developer Code Samples(开发人员代码示例)下载了编码,请打开 AsyncWalkthrough 项目,然后将 ProcessURLAsync 添加到 MainWindow.xaml.vb 或 MainWindow.xaml.cs 文件。
如果您已通过完成该演练开发代码,请将 ProcessURLAsync 添加到包含 GetURLContentsAsync 方法的应用程序。 此应用程序的 MainWindow.xaml.vb 或 MainWindow.xaml.cs 文件是“从演练完成代码示例”部分中的第一个示例。
ProcessURLAsync 方法合并了 For Each 或原始演练中 SumPageSizesAsync 中的 foreach 循环的主体中的操作。 该方法异步下载指定网站的内容作为字节数组,然后显示并返回字节数组的长度。
Private Async Function ProcessURLAsync(url As String) As Task(Of Integer) Dim byteArray = Await GetURLContentsAsync(url) DisplayResults(url, byteArray) Return byteArray.Length End Function
private async Task<int> ProcessURLAsync(string url) { var byteArray = await GetURLContentsAsync(url); DisplayResults(url, byteArray); return byteArray.Length; }
注释掉或删除 For Each 或 foreach 循环(在 SumPageSizesAsync 中),如下面的代码所示。
'Dim total = 0 'For Each url In urlList ' Dim urlContents As Byte() = Await GetURLContentsAsync(url) ' ' The previous line abbreviates the following two assignment statements. ' ' GetURLContentsAsync returns a task. At completion, the task ' ' produces a byte array. ' 'Dim getContentsTask As Task(Of Byte()) = GetURLContentsAsync(url) ' 'Dim urlContents As Byte() = Await getContentsTask ' DisplayResults(url, urlContents) ' ' Update the total. ' total += urlContents.Length 'Next
//var total = 0; //foreach (var url in urlList) //{ // byte[] urlContents = await GetURLContentsAsync(url); // // The previous line abbreviates the following two assignment statements. // // GetURLContentsAsync returns a Task<T>. At completion, the task // // produces a byte array. // //Task<byte[]> getContentsTask = GetURLContentsAsync(url); // //byte[] urlContents = await getContentsTask; // DisplayResults(url, urlContents); // // Update the total. // total += urlContents.Length; //}
创建任务集合。 下面的代码定义查询,此查询在由 ToArray``1 方法执行时,创建下载每个网站内容的任务集合。 在计算该查询时,任务启动。
在 urlList 声明后,将下列的代码添加到方法 SumPageSizesAsync 中。
' Create a query. Dim downloadTasksQuery As IEnumerable(Of Task(Of Integer)) = From url In urlList Select ProcessURLAsync(url) ' Use ToArray to execute the query and start the download tasks. Dim downloadTasks As Task(Of Integer)() = downloadTasksQuery.ToArray()
// Create a query. IEnumerable<Task<int>> downloadTasksQuery = from url in urlList select ProcessURLAsync(url); // Use ToArray to execute the query and start the download tasks. Task<int>[] downloadTasks = downloadTasksQuery.ToArray();
将 Task.WhenAll 应用于任务集合,downloadTasks。 Task.WhenAll 返回当任务的集合中所有任务完成时完成的单个任务。
在下面的示例中,Await 或 await 表达式等待完成 WhenAll 返回的单个任务。 该表达式计算为整数数组,其中每个整数都是一个下载网站的长度。 在上一步中添加的代码后,将下列的代码添加到 SumPageSizesAsync 中。
' Await the completion of all the running tasks. Dim lengths As Integer() = Await Task.WhenAll(downloadTasks) '' The previous line is equivalent to the following two statements. 'Dim whenAllTask As Task(Of Integer()) = Task.WhenAll(downloadTasks) 'Dim lengths As Integer() = Await whenAllTask
// Await the completion of all the running tasks. int[] lengths = await Task.WhenAll(downloadTasks); //// The previous line is equivalent to the following two statements. //Task<int[]> whenAllTask = Task.WhenAll(downloadTasks); //int[] lengths = await whenAllTask;
最后,使用 Sum 方法来计算所有网站的总长度。 将下列行添加到 SumPageSizesAsync。
Dim total = lengths.Sum()
int total = lengths.Sum();
向 HttpClient.GetByteArrayAsync 解决方案中添加 Task.WhenAll
添加 ProcessURLAsync 的以下版本到在 演练:使用 Async 和 Await 访问 Web(C# 和 Visual Basic) 中开发的第二个应用程序。
如果您已从 Developer Code Samples(开发人员代码示例)下载了编码,请打开 AsyncWalkthrough_HttpClient 项目,然后将 ProcessURLAsync 添加到 MainWindow.xaml.vb 或 MainWindow.xaml.cs 文件。
如果您已通过完成该演练开发代码,请将 ProcessURLAsync 添加到使用 HttpClient.GetByteArrayAsync 方法的应用程序。 此应用程序的 MainWindow.xaml.vb 或 MainWindow.xaml.cs 文件是“从演练完成代码示例”部分中的第二个示例。
ProcessURLAsync 方法合并了 For Each 或原始演练中 SumPageSizesAsync 中的 foreach 循环的主体中的操作。 该方法异步下载指定网站的内容作为字节数组,然后显示并返回字节数组的长度。
在前面的过程中,ProcessURLAsync 方法的唯一区别是使用 HttpClient 实例,client。
Private Async Function ProcessURLAsync(url As String, client As HttpClient) As Task(Of Integer) Dim byteArray = Await client.GetByteArrayAsync(url) DisplayResults(url, byteArray) Return byteArray.Length End Function
async Task<int> ProcessURL(string url, HttpClient client) { byte[] byteArray = await client.GetByteArrayAsync(url); DisplayResults(url, byteArray); return byteArray.Length; }
注释掉或删除 For Each 或 foreach 循环(在 SumPageSizesAsync 中),如下面的代码所示。
'Dim total = 0 'For Each url In urlList ' ' GetByteArrayAsync returns a task. At completion, the task ' ' produces a byte array. ' Dim urlContents As Byte() = Await client.GetByteArrayAsync(url) ' ' The following two lines can replace the previous assignment statement. ' 'Dim getContentsTask As Task(Of Byte()) = client.GetByteArrayAsync(url) ' 'Dim urlContents As Byte() = Await getContentsTask ' DisplayResults(url, urlContents) ' ' Update the total. ' total += urlContents.Length 'Next
//var total = 0; //foreach (var url in urlList) //{ // // GetByteArrayAsync returns a Task<T>. At completion, the task // // produces a byte array. // byte[] urlContent = await client.GetByteArrayAsync(url); // // The previous line abbreviates the following two assignment // // statements. // Task<byte[]> getContentTask = client.GetByteArrayAsync(url); // byte[] urlContent = await getContentTask; // DisplayResults(url, urlContent); // // Update the total. // total += urlContent.Length; //}
定义查询,此查询在由 ToArray``1 方法执行时,创建下载每个网站内容的任务集合。 在计算该查询时,任务启动。
在 client 和 urlList 声明后,将下列的代码添加到方法 SumPageSizesAsync 中。
' Create a query. Dim downloadTasksQuery As IEnumerable(Of Task(Of Integer)) = From url In urlList Select ProcessURLAsync(url, client) ' Use ToArray to execute the query and start the download tasks. Dim downloadTasks As Task(Of Integer)() = downloadTasksQuery.ToArray()
// Create a query. IEnumerable<Task<int>> downloadTasksQuery = from url in urlList select ProcessURL(url, client); // Use ToArray to execute the query and start the download tasks. Task<int>[] downloadTasks = downloadTasksQuery.ToArray();
下一步,将 Task.WhenAll 应用于任务集合,downloadTasks。 Task.WhenAll 返回当任务的集合中所有任务完成时完成的单个任务。
在下面的示例中,Await 或 await 表达式等待完成 WhenAll 返回的单个任务。 完成后,Await 或 await 表达式的计算结果为整数数组,其中每个整数都是一个下载网站的长度。 在上一步中添加的代码后,将下列的代码添加到 SumPageSizesAsync 中。
' Await the completion of all the running tasks. Dim lengths As Integer() = Await Task.WhenAll(downloadTasks) '' The previous line is equivalent to the following two statements. 'Dim whenAllTask As Task(Of Integer()) = Task.WhenAll(downloadTasks) 'Dim lengths As Integer() = Await whenAllTask
// Await the completion of all the running tasks. int[] lengths = await Task.WhenAll(downloadTasks); //// The previous line is equivalent to the following two statements. //Task<int[]> whenAllTask = Task.WhenAll(downloadTasks); //int[] lengths = await whenAllTask;
最后,使用 Sum 方法来获取所有网站的总长度。 将下列行添加到 SumPageSizesAsync。
Dim total = lengths.Sum()
int total = lengths.Sum();
测试 Task.WhenAll 解决方案
- 对于每一个解决方案,请选择 F5 键运行程序,然后选择“开始”按钮。 输出应类似于 演练:使用 Async 和 Await 访问 Web(C# 和 Visual Basic) 中异步解决方案的输出。 但请注意,网站每次以不同的顺序显示。
示例
下面的代码显示使用 GetURLContentsAsync 方法从 web 下载内容的项目的扩展。
' Add the following Imports statements, and add a reference for System.Net.Http.
Imports System.Net.Http
Imports System.Net
Imports System.IO
Class MainWindow
Async Sub startButton_Click(sender As Object, e As RoutedEventArgs) Handles startButton.Click
resultsTextBox.Clear()
' One-step async call.
Await SumPageSizesAsync()
'' Two-step async call.
'Dim sumTask As Task = SumPageSizesAsync()
'Await sumTask
resultsTextBox.Text &= vbCrLf & "Control returned to button1_Click."
End Sub
Private Async Function SumPageSizesAsync() As Task
' Make a list of web addresses.
Dim urlList As List(Of String) = SetUpURLList()
' Create a query.
Dim downloadTasksQuery As IEnumerable(Of Task(Of Integer)) =
From url In urlList Select ProcessURLAsync(url)
' Use ToArray to execute the query and start the download tasks.
Dim downloadTasks As Task(Of Integer)() = downloadTasksQuery.ToArray()
' You can do other work here before awaiting.
' Await the completion of all the running tasks.
Dim lengths As Integer() = Await Task.WhenAll(downloadTasks)
'' The previous line is equivalent to the following two statements.
'Dim whenAllTask As Task(Of Integer()) = Task.WhenAll(downloadTasks)
'Dim lengths As Integer() = Await whenAllTask
Dim total = lengths.Sum()
'Dim total = 0
'For Each url In urlList
' Dim urlContents As Byte() = Await GetURLContentsAsync(url)
' ' The previous line abbreviates the following two assignment statements.
' ' GetURLContentsAsync returns a task. At completion, the task
' ' produces a byte array.
' 'Dim getContentsTask As Task(Of Byte()) = GetURLContentsAsync(url)
' 'Dim urlContents As Byte() = Await getContentsTask
' DisplayResults(url, urlContents)
' ' Update the total.
' total += urlContents.Length
'Next
' Display the total count for all of the web addresses.
resultsTextBox.Text &= String.Format(vbCrLf & vbCrLf &
"Total bytes returned: {0}" & vbCrLf, total)
End Function
Private Function SetUpURLList() As List(Of String)
Dim urls = New List(Of String) From
{
"https://msdn.microsoft.com",
"https://msdn.microsoft.com/en-us/library/hh290136.aspx",
"https://msdn.microsoft.com/en-us/library/ee256749.aspx",
"https://msdn.microsoft.com/en-us/library/hh290138.aspx",
"https://msdn.microsoft.com/en-us/library/hh290140.aspx",
"https://msdn.microsoft.com/en-us/library/dd470362.aspx",
"https://msdn.microsoft.com/en-us/library/aa578028.aspx",
"https://msdn.microsoft.com/en-us/library/ms404677.aspx",
"https://msdn.microsoft.com/en-us/library/ff730837.aspx"
}
Return urls
End Function
' The actions from the foreach loop are moved to this async method.
Private Async Function ProcessURLAsync(url As String) As Task(Of Integer)
Dim byteArray = Await GetURLContentsAsync(url)
DisplayResults(url, byteArray)
Return byteArray.Length
End Function
Private Async Function GetURLContentsAsync(url As String) As Task(Of Byte())
' The downloaded resource ends up in the variable named content.
Dim content = New MemoryStream()
' Initialize an HttpWebRequest for the current URL.
Dim webReq = CType(WebRequest.Create(url), HttpWebRequest)
' Send the request to the Internet resource and wait for
' the response.
Using response As WebResponse = Await webReq.GetResponseAsync()
' Get the data stream that is associated with the specified URL.
Using responseStream As Stream = response.GetResponseStream()
' Read the bytes in responseStream and copy them to content.
' CopyToAsync returns a Task, not a Task<T>.
Await responseStream.CopyToAsync(content)
End Using
End Using
' Return the result as a byte array.
Return content.ToArray()
End Function
Private Sub DisplayResults(url As String, content As Byte())
' 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.
Dim bytes = content.Length
' Strip off the "http://".
Dim displayURL = url.Replace("http://", "")
resultsTextBox.Text &= String.Format(vbCrLf & "{0,-58} {1,8}", displayURL, bytes)
End Sub
End Class
// Add the following using directives, and add a reference for System.Net.Http.
using System.Net.Http;
using System.IO;
using System.Net;
namespace AsyncExampleWPF_WhenAll
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private async void startButton_Click(object sender, RoutedEventArgs e)
{
resultsTextBox.Clear();
// Two-step async call.
Task sumTask = SumPageSizesAsync();
await sumTask;
// One-step async call.
//await SumPageSizesAsync();
resultsTextBox.Text += "\r\nControl returned to startButton_Click.\r\n";
}
private async Task SumPageSizesAsync()
{
// Make a list of web addresses.
List<string> urlList = SetUpURLList();
// Create a query.
IEnumerable<Task<int>> downloadTasksQuery =
from url in urlList select ProcessURLAsync(url);
// Use ToArray to execute the query and start the download tasks.
Task<int>[] downloadTasks = downloadTasksQuery.ToArray();
// You can do other work here before awaiting.
// Await the completion of all the running tasks.
int[] lengths = await Task.WhenAll(downloadTasks);
//// The previous line is equivalent to the following two statements.
//Task<int[]> whenAllTask = Task.WhenAll(downloadTasks);
//int[] lengths = await whenAllTask;
int total = lengths.Sum();
//var total = 0;
//foreach (var url in urlList)
//{
// byte[] urlContents = await GetURLContentsAsync(url);
// // The previous line abbreviates the following two assignment statements.
// // GetURLContentsAsync returns a Task<T>. At completion, the task
// // produces a byte array.
// //Task<byte[]> getContentsTask = GetURLContentsAsync(url);
// //byte[] urlContents = await getContentsTask;
// DisplayResults(url, urlContents);
// // Update the total.
// total += urlContents.Length;
//}
// Display the total count for all of the websites.
resultsTextBox.Text +=
string.Format("\r\n\r\nTotal bytes returned: {0}\r\n", total);
}
private List<string> SetUpURLList()
{
List<string> urls = new List<string>
{
"https://msdn.microsoft.com",
"https://msdn.microsoft.com/library/windows/apps/br211380.aspx",
"https://msdn.microsoft.com/en-us/library/hh290136.aspx",
"https://msdn.microsoft.com/en-us/library/ee256749.aspx",
"https://msdn.microsoft.com/en-us/library/hh290138.aspx",
"https://msdn.microsoft.com/en-us/library/hh290140.aspx",
"https://msdn.microsoft.com/en-us/library/dd470362.aspx",
"https://msdn.microsoft.com/en-us/library/aa578028.aspx",
"https://msdn.microsoft.com/en-us/library/ms404677.aspx",
"https://msdn.microsoft.com/en-us/library/ff730837.aspx"
};
return urls;
}
// The actions from the foreach loop are moved to this async method.
private async Task<int> ProcessURLAsync(string url)
{
var byteArray = await GetURLContentsAsync(url);
DisplayResults(url, byteArray);
return byteArray.Length;
}
private async Task<byte[]> GetURLContentsAsync(string url)
{
// The downloaded resource ends up in the variable named content.
var content = new MemoryStream();
// Initialize an HttpWebRequest for the current URL.
var webReq = (HttpWebRequest)WebRequest.Create(url);
// Send the request to the Internet resource and wait for
// the response.
using (WebResponse response = await webReq.GetResponseAsync())
{
// Get the data stream that is associated with the specified url.
using (Stream responseStream = response.GetResponseStream())
{
await responseStream.CopyToAsync(content);
}
}
// Return the result as a byte array.
return content.ToArray();
}
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);
}
}
}
下面的代码显示使用方法 HttpClient.GetByteArrayAsync 从 web 下载内容的项目的扩展。
' Add the following Imports statements, and add a reference for System.Net.Http.
Imports System.Net.Http
Imports System.Net
Imports System.IO
Class MainWindow
Async Sub startButton_Click(sender As Object, e As RoutedEventArgs) Handles startButton.Click
resultsTextBox.Clear()
'' One-step async call.
Await SumPageSizesAsync()
'' Two-step async call.
'Dim sumTask As Task = SumPageSizesAsync()
'Await sumTask
resultsTextBox.Text &= vbCrLf & "Control returned to button1_Click."
End Sub
Private Async Function SumPageSizesAsync() As Task
' Declare an HttpClient object and increase the buffer size. The
' default buffer size is 65,536.
Dim client As HttpClient =
New HttpClient() With {.MaxResponseContentBufferSize = 1000000}
' Make a list of web addresses.
Dim urlList As List(Of String) = SetUpURLList()
' Create a query.
Dim downloadTasksQuery As IEnumerable(Of Task(Of Integer)) =
From url In urlList Select ProcessURLAsync(url, client)
' Use ToArray to execute the query and start the download tasks.
Dim downloadTasks As Task(Of Integer)() = downloadTasksQuery.ToArray()
' You can do other work here before awaiting.
' Await the completion of all the running tasks.
Dim lengths As Integer() = Await Task.WhenAll(downloadTasks)
'' The previous line is equivalent to the following two statements.
'Dim whenAllTask As Task(Of Integer()) = Task.WhenAll(downloadTasks)
'Dim lengths As Integer() = Await whenAllTask
Dim total = lengths.Sum()
'Dim total = 0
'For Each url In urlList
' ' GetByteArrayAsync returns a task. At completion, the task
' ' produces a byte array.
' Dim urlContents As Byte() = Await client.GetByteArrayAsync(url)
' ' The following two lines can replace the previous assignment statement.
' 'Dim getContentsTask As Task(Of Byte()) = client.GetByteArrayAsync(url)
' 'Dim urlContents As Byte() = Await getContentsTask
' DisplayResults(url, urlContents)
' ' Update the total.
' total += urlContents.Length
'Next
' Display the total count for all of the web addresses.
resultsTextBox.Text &= String.Format(vbCrLf & vbCrLf &
"Total bytes returned: {0}" & vbCrLf, total)
End Function
Private Function SetUpURLList() As List(Of String)
Dim urls = New List(Of String) From
{
"http://www.msdn.com",
"https://msdn.microsoft.com/en-us/library/hh290136.aspx",
"https://msdn.microsoft.com/en-us/library/ee256749.aspx",
"https://msdn.microsoft.com/en-us/library/hh290138.aspx",
"https://msdn.microsoft.com/en-us/library/hh290140.aspx",
"https://msdn.microsoft.com/en-us/library/dd470362.aspx",
"https://msdn.microsoft.com/en-us/library/aa578028.aspx",
"https://msdn.microsoft.com/en-us/library/ms404677.aspx",
"https://msdn.microsoft.com/en-us/library/ff730837.aspx"
}
Return urls
End Function
Private Async Function ProcessURLAsync(url As String, client As HttpClient) As Task(Of Integer)
Dim byteArray = Await client.GetByteArrayAsync(url)
DisplayResults(url, byteArray)
Return byteArray.Length
End Function
Private Sub DisplayResults(url As String, content As Byte())
' 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.
Dim bytes = content.Length
' Strip off the "http://".
Dim displayURL = url.Replace("http://", "")
resultsTextBox.Text &= String.Format(vbCrLf & "{0,-58} {1,8}", displayURL, bytes)
End Sub
End Class
// Add the following using directives, and add a reference for System.Net.Http.
using System.Net.Http;
using System.IO;
using System.Net;
namespace AsyncExampleWPF_HttpClient_WhenAll
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private async void startButton_Click(object sender, RoutedEventArgs e)
{
resultsTextBox.Clear();
// One-step async call.
await SumPageSizesAsync();
// Two-step async call.
//Task sumTask = SumPageSizesAsync();
//await sumTask;
resultsTextBox.Text += "\r\nControl returned to startButton_Click.\r\n";
}
private async Task SumPageSizesAsync()
{
// Make a list of web addresses.
List<string> urlList = SetUpURLList();
// Declare an HttpClient object and increase the buffer size. The
// default buffer size is 65,536.
HttpClient client = new HttpClient() { MaxResponseContentBufferSize = 1000000 };
// Create a query.
IEnumerable<Task<int>> downloadTasksQuery =
from url in urlList select ProcessURL(url, client);
// Use ToArray to execute the query and start the download tasks.
Task<int>[] downloadTasks = downloadTasksQuery.ToArray();
// You can do other work here before awaiting.
// Await the completion of all the running tasks.
int[] lengths = await Task.WhenAll(downloadTasks);
//// The previous line is equivalent to the following two statements.
//Task<int[]> whenAllTask = Task.WhenAll(downloadTasks);
//int[] lengths = await whenAllTask;
int total = lengths.Sum();
//var total = 0;
//foreach (var url in urlList)
//{
// // GetByteArrayAsync returns a Task<T>. At completion, the task
// // produces a byte array.
// byte[] urlContent = await client.GetByteArrayAsync(url);
// // The previous line abbreviates the following two assignment
// // statements.
// Task<byte[]> getContentTask = client.GetByteArrayAsync(url);
// byte[] urlContent = await getContentTask;
// DisplayResults(url, urlContent);
// // Update the total.
// total += urlContent.Length;
//}
// Display the total count for all of the web addresses.
resultsTextBox.Text +=
string.Format("\r\n\r\nTotal bytes returned: {0}\r\n", total);
}
private List<string> SetUpURLList()
{
List<string> urls = new List<string>
{
"https://msdn.microsoft.com",
"https://msdn.microsoft.com/en-us/library/hh290136.aspx",
"https://msdn.microsoft.com/en-us/library/ee256749.aspx",
"https://msdn.microsoft.com/en-us/library/hh290138.aspx",
"https://msdn.microsoft.com/en-us/library/hh290140.aspx",
"https://msdn.microsoft.com/en-us/library/dd470362.aspx",
"https://msdn.microsoft.com/en-us/library/aa578028.aspx",
"https://msdn.microsoft.com/en-us/library/ms404677.aspx",
"https://msdn.microsoft.com/en-us/library/ff730837.aspx"
};
return urls;
}
// The actions from the foreach loop are moved to this async method.
async Task<int> ProcessURL(string url, HttpClient client)
{
byte[] byteArray = await client.GetByteArrayAsync(url);
DisplayResults(url, byteArray);
return byteArray.Length;
}
private void DisplayResults(string url, byte[] content)
{
// Display the length of each web site. 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 和 Await 访问 Web(C# 和 Visual Basic)