流浪のwolf

卷帝

导航

Csharp的CancellationToken 案例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

// 命名空间
namespace pro01
{
    //
    internal class Program
    {
        // main 方法
        static async Task Main(string[] args)
        {
            Console.WriteLine("=======测试CancellationToken=========");
            CancellationTokenSource cts = new CancellationTokenSource();
            cts.CancelAfter(3000);
            CancellationToken cToken = cts.Token;
            await DownLoadAsync("https://www.baidu.com", 200
                , cToken);
            Console.ReadLine();
        }

        /// <summary>
        /// 下载网页内容的函数
        /// </summary>
        /// <param name="url"></param>
        /// <param name="n"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        static async Task DownLoadAsync(string url ,int n, CancellationToken cancellationToken)
        {
            using (HttpClient client = new HttpClient())
            {
                for(int i = 0;i < n;i++)
                {
                    //GetStringAsync 使用异步的方法 从 url 下载 内容
                    string html = await client.GetStringAsync(url);
                    Console.WriteLine($"{DateTime.Now}:{html}");  // print container
                    if (cancellationToken.IsCancellationRequested)  // 监听是否取消了
                    {
                        Console.WriteLine("请求取消了");
                        break;
                    }
                }
            }
        }
    }
}

 

posted on 2023-07-01 13:19  流浪のwolf  阅读(8)  评论(0编辑  收藏  举报