完整示例 (控制台)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
await JobsAsync();
Console.WriteLine("Application ending.");
Console.ReadKey();
}
static async Task JobsAsync()
{
CancellationTokenSource s_cts = new CancellationTokenSource();
HttpClient s_client = new HttpClient();
IEnumerable<string> s_urlList = new string[]
{
"https://docs.microsoft.com",
"https://docs.microsoft.com/aspnet/core",
"https://docs.microsoft.com/azure",
"https://docs.microsoft.com/azure/devops",
"https://docs.microsoft.com/dotnet",
};
var tasks = new List<Task>();
foreach (var url in s_urlList)
{
tasks.Add(ProcessUrlAsync(url, s_client, s_cts.Token));
}
await Task.WhenAll(tasks);
}
static async Task ProcessUrlAsync(string url, HttpClient client, CancellationToken token)
{
HttpResponseMessage response = await client.GetAsync(url, token);
byte[] content = await response.Content.ReadAsByteArrayAsync(token);
Console.WriteLine($"{url,-60} {content.Length,10:#,#}");
//处理结果
//......
}
}
任务处理
static async Task ProcessUrlAsync(string url, HttpClient client, CancellationToken token)
{
HttpResponseMessage response = await client.GetAsync(url, token);
byte[] content = await response.Content.ReadAsByteArrayAsync(token);
Console.WriteLine($"{url,-60} {content.Length,10:#,#}");
//处理结果
//......
}
任务入列
static async Task JobsAsync()
{
CancellationTokenSource s_cts = new CancellationTokenSource();
HttpClient s_client = new HttpClient();
IEnumerable<string> s_urlList = new string[]
{
"https://docs.microsoft.com",
"https://docs.microsoft.com/aspnet/core",
"https://docs.microsoft.com/azure",
"https://docs.microsoft.com/azure/devops",
"https://docs.microsoft.com/dotnet",
};
var tasks = new List<Task>();
foreach (var url in s_urlList)
{
tasks.Add(ProcessUrlAsync(url, s_client, s_cts.Token));
}
await Task.WhenAll(tasks);
}
控制台调用
static async Task Main()
{
await JobsAsync();
Console.WriteLine("Application ending.");
Console.ReadKey();
}