终止异步方法的实现主要依靠 CancellationToken 类
using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp21 { internal class Program { static async Task Main(string[] args) { CancellationTokenSource source = new CancellationTokenSource(); source.CancelAfter(2000); //2000毫秒 CancellationToken ct = source.Token; await DownloadAsync("https://www.bilibili.com/", 10, ct); Console.ReadLine(); } /// <summary> /// 从网址循环下载网页内容 /// </summary> /// <param name="url">网址</param> /// <param name="n">下载次数</param> /// <param name="token">令牌</param> /// <returns></returns> static async Task DownloadAsync(string url, int n, CancellationToken token) { using (HttpClient http = new HttpClient()) { string str = string.Empty; for (int i = 0; i < n; i++) { // 方法1:在传入参数的时间范围内还没完成请求则终止本次任务 //if (token.IsCancellationRequested) //{ // Console.WriteLine(); // Console.WriteLine("请求被提前终止!"); // break; //} str = await http.GetStringAsync(url); Console.WriteLine(str); //方法2:在传入参数的时间范围内还没完成请求则返回一个错误 //token.ThrowIfCancellationRequested(); //方法3:把token传给需要调用的方法 await http.GetAsync(url, token); } } } } }