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.
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|