You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

30 lines
971 B
C#

namespace cancelAsync
{
internal class Program
{
static async Task Main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(2));
await DownloadAsync("http://baidu.com", 200, cts.Token);
}
static async Task DownloadAsync(string url, int num, CancellationToken cancellationToken)
{
using (var client = new HttpClient())
{
for (int i = 0; i < num; i++)
{
string html = await client.GetStringAsync(url);
Console.WriteLine($"{DateTime.Now}: {html}");
if (cancellationToken.IsCancellationRequested)
{
Console.WriteLine($"{DateTime.Now}: 异步取消完成");
break;
}
}
}
}
}
}