c# - CancellationToken Demo

using System;
using System.Threading;
using System.Threading.Tasks;

namespace TaskCancellationTest
{
    class Program
    {
        static void Main(string[] args)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            

            Handle(cts.Token);

            Console.WriteLine("Press <Enter> to cancel tasks.");
            Console.ReadLine();

            cts.Cancel();

            // Won't stop
            Console.ReadLine();
        }

        public static async void Handle(CancellationToken ct)
        {
            for (int i = 0; i < 10; i++)
            {
                try
                {
                    ct.ThrowIfCancellationRequested();
                    await Task.Delay(1000);
                    Console.WriteLine($"Taks {i} has completed.");
                }
                catch (Exception ex) when (ex is OperationCanceledException)
                {
                    Console.WriteLine("Task was cancelled.");
                    return;
                }
            }
        }
    }
}
发布了130 篇原创文章 · 获赞 20 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/yuxuac/article/details/103841828
今日推荐