通过使用 Task.WhenAny,可以同时启动多个任务,并在完成时逐个处理它们,而不是按照启动顺序处理它们。
以下示例使用查询创建任务集合。 每个任务都会下载指定网站的内容。 在 while 循环的每个迭代中,等待的调用将 WhenAny 返回任务集合中首先完成下载的任务。 该任务已从集合中删除并处理。 循环重复,直到集合不包含更多任务。
先决条件
可以使用以下选项之一来遵循本教程:
- 已安装 .NET 桌面开发工作负载的 Visual Studio 2022。 选择此工作负荷时,将自动安装 .NET SDK。
- 具有所选代码编辑器的 .NET SDK ,例如 Visual Studio Code。
创建示例应用程序
创建新的 .NET Core 控制台应用程序。 可以使用 dotnet new console 命令或 Visual Studio 创建一个。
在代码编辑器中打开 Program.cs 文件,并将现有代码替换为以下代码:
using System.Diagnostics;
namespace ProcessTasksAsTheyFinish;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
添加字段
在 Program 类定义中,添加以下两个字段:
static readonly HttpClient s_client = new HttpClient
{
MaxResponseContentBufferSize = 1_000_000
};
static readonly IEnumerable<string> s_urlList = new string[]
{
"https://learn.microsoft.com",
"https://learn.microsoft.com/aspnet/core",
"https://learn.microsoft.com/azure",
"https://learn.microsoft.com/azure/devops",
"https://learn.microsoft.com/dotnet",
"https://learn.microsoft.com/dynamics365",
"https://learn.microsoft.com/education",
"https://learn.microsoft.com/enterprise-mobility-security",
"https://learn.microsoft.com/gaming",
"https://learn.microsoft.com/graph",
"https://learn.microsoft.com/microsoft-365",
"https://learn.microsoft.com/office",
"https://learn.microsoft.com/powershell",
"https://learn.microsoft.com/sql",
"https://learn.microsoft.com/surface",
"https://learn.microsoft.com/system-center",
"https://learn.microsoft.com/visualstudio",
"https://learn.microsoft.com/windows",
"https://learn.microsoft.com/maui"
};
公开 HttpClient 发送 HTTP 请求和接收 HTTP 响应的功能。
s_urlList 存储了应用程序计划处理的所有 URL。
更新应用程序入口点
控制台应用程序的主要入口点是 Main 方法。 将现有方法替换为以下内容:
static Task Main() => SumPageSizesAsync();
更新的 Main 方法现在被视为 异步主方法,这允许在可执行文件中实现异步入口点。 它以调用 SumPageSizesAsync的形式表示。
创建异步计算页大小总和值的方法
在 Main 方法下方,添加 SumPageSizesAsync 方法:
static async Task SumPageSizesAsync()
{
var stopwatch = Stopwatch.StartNew();
IEnumerable<Task<int>> downloadTasksQuery =
from url in s_urlList
select ProcessUrlAsync(url, s_client);
List<Task<int>> downloadTasks = downloadTasksQuery.ToList();
int total = 0;
while (downloadTasks.Any())
{
Task<int> finishedTask = await Task.WhenAny(downloadTasks);
downloadTasks.Remove(finishedTask);
total += await finishedTask;
}
stopwatch.Stop();
Console.WriteLine($"\nTotal bytes returned: {total:#,#}");
Console.WriteLine($"Elapsed time: {stopwatch.Elapsed}\n");
}
循环 while 会删除每次迭代中的一个任务。 完成每个任务后,循环将结束。 该方法首先实例化并启动Stopwatch。 然后,它包含一个查询,在执行时会创建任务集合。 以下代码中每次调用 ProcessUrlAsync 都会返回一个 Task<TResult>整数,其中 TResult 为整数:
IEnumerable<Task<int>> downloadTasksQuery =
from url in s_urlList
select ProcessUrlAsync(url, s_client);
由于 LINQ 执行延迟 ,因此调用 Enumerable.ToList 启动每个任务。
List<Task<int>> downloadTasks = downloadTasksQuery.ToList();
该 while 循环针对集合中的每个任务执行以下步骤:
等待调用
WhenAny以识别集合中第一个完成下载的任务。Task<int> finishedTask = await Task.WhenAny(downloadTasks);从集合中删除该任务。
downloadTasks.Remove(finishedTask);等待
finishedTask,由调用ProcessUrlAsync返回。 变量finishedTask是一个Task<TResult>类型,其中TResult是一个整数。 任务已经完成,但你等待它检索下载的网站长度,如以下示例所示。 如果任务出错,await将引发存储在AggregateException中的第一个子异常,这与读取 Task<TResult>.Result 属性不同,读取它会引发AggregateException属性中的异常。total += await finishedTask;
添加进程方法
在SumPageSizesAsync方法下方添加以下ProcessUrlAsync方法:
static async Task<int> ProcessUrlAsync(string url, HttpClient client)
{
byte[] content = await client.GetByteArrayAsync(url);
Console.WriteLine($"{url,-60} {content.Length,10:#,#}");
return content.Length;
}
对于任意给定的 URL,该方法将使用 client 提供的实例以 byte[] 形式获取响应。 控制台写入 URL 和长度后,长度被返回。
多次运行程序,验证下载的长度并不总是以相同的顺序显示。
注意
如示例中所述,可以在循环中使用 WhenAny ,以解决涉及少量任务的问题。 但是,如果你有大量要处理的任务,则其他方法更高效。 有关详细信息和示例,请参阅处理任务的完成。
简化处理方法使用 Task.WhenEach
在while方法中实现的循环可以通过在await foreach循环中调用 .NET 9 引入的新Task.WhenEach方法来简化。
替换之前实现的 while 循环:
while (downloadTasks.Any())
{
Task<int> finishedTask = await Task.WhenAny(downloadTasks);
downloadTasks.Remove(finishedTask);
total += await finishedTask;
}
使用简化的await foreach:
await foreach (Task<int> t in Task.WhenEach(downloadTasks))
{
total += await t;
}
这种新方法允许不再需要重复调用Task.WhenAny来手动启动任务和删除已完成的任务,因为Task.WhenEach会按任务完成的顺序迭代这些任务。
完整示例
以下代码是示例 Program.cs 文件的完整文本。
using System.Diagnostics;
HttpClient s_client = new()
{
MaxResponseContentBufferSize = 1_000_000
};
IEnumerable<string> s_urlList = new string[]
{
"https://learn.microsoft.com",
"https://learn.microsoft.com/aspnet/core",
"https://learn.microsoft.com/azure",
"https://learn.microsoft.com/azure/devops",
"https://learn.microsoft.com/dotnet",
"https://learn.microsoft.com/dynamics365",
"https://learn.microsoft.com/education",
"https://learn.microsoft.com/enterprise-mobility-security",
"https://learn.microsoft.com/gaming",
"https://learn.microsoft.com/graph",
"https://learn.microsoft.com/microsoft-365",
"https://learn.microsoft.com/office",
"https://learn.microsoft.com/powershell",
"https://learn.microsoft.com/sql",
"https://learn.microsoft.com/surface",
"https://learn.microsoft.com/system-center",
"https://learn.microsoft.com/visualstudio",
"https://learn.microsoft.com/windows",
"https://learn.microsoft.com/maui"
};
await SumPageSizesAsync();
async Task SumPageSizesAsync()
{
var stopwatch = Stopwatch.StartNew();
IEnumerable<Task<int>> downloadTasksQuery =
from url in s_urlList
select ProcessUrlAsync(url, s_client);
List<Task<int>> downloadTasks = downloadTasksQuery.ToList();
int total = 0;
while (downloadTasks.Any())
{
Task<int> finishedTask = await Task.WhenAny(downloadTasks);
downloadTasks.Remove(finishedTask);
total += await finishedTask;
}
stopwatch.Stop();
Console.WriteLine($"\nTotal bytes returned: {total:#,#}");
Console.WriteLine($"Elapsed time: {stopwatch.Elapsed}\n");
}
static async Task<int> ProcessUrlAsync(string url, HttpClient client)
{
byte[] content = await client.GetByteArrayAsync(url);
Console.WriteLine($"{url,-60} {content.Length,10:#,#}");
return content.Length;
}
// Example output:
// https://learn.microsoft.com 132,517
// https://learn.microsoft.com/powershell 57,375
// https://learn.microsoft.com/gaming 33,549
// https://learn.microsoft.com/aspnet/core 88,714
// https://learn.microsoft.com/surface 39,840
// https://learn.microsoft.com/enterprise-mobility-security 30,903
// https://learn.microsoft.com/microsoft-365 67,867
// https://learn.microsoft.com/windows 26,816
// https://learn.microsoft.com/maui 57,958
// https://learn.microsoft.com/dotnet 78,706
// https://learn.microsoft.com/graph 48,277
// https://learn.microsoft.com/dynamics365 49,042
// https://learn.microsoft.com/office 67,867
// https://learn.microsoft.com/system-center 42,887
// https://learn.microsoft.com/education 38,636
// https://learn.microsoft.com/azure 421,663
// https://learn.microsoft.com/visualstudio 30,925
// https://learn.microsoft.com/sql 54,608
// https://learn.microsoft.com/azure/devops 86,034
// Total bytes returned: 1,454,184
// Elapsed time: 00:00:01.1290403