首页 > 其他分享 >CancellationTokenSource

CancellationTokenSource

时间:2022-11-14 00:12:00浏览次数:50  
标签:cancelSource Console DateTime CancellationTokenSource WriteLine new

 

public static void work(CancellationToken cancellation)
{
    Thread.Sleep(10000);
    //while (true)
    //{
        Console.WriteLine("结束" + DateTime.Now.ToString("yyyyMMddHHmmss"));
        if (cancellation.IsCancellationRequested)
        {
            throw new OperationCanceledException("结束");
        }
    //}
}
static void Main(string[] args)
{
    {
        Console.WriteLine("开始" + DateTime.Now.ToString("yyyyMMddHHmmss"));
        var cancelSource = new CancellationTokenSource();
        cancelSource.CancelAfter(30000);
        var t = new Thread(() =>
        {
            try
            {
                work(cancelSource.Token);
            }
            catch (OperationCanceledException e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
        });
        t.Start();
        t.Join();
        Console.WriteLine(t.ThreadState);
        Console.WriteLine(t.IsAlive);
    }
}

 

标签:cancelSource,Console,DateTime,CancellationTokenSource,WriteLine,new
From: https://www.cnblogs.com/ZkbFighting/p/16887782.html

相关文章

  • C# 使用CancellationTokenSource取消多线程
    原文网址:https://blog.csdn.net/xwnxwn/article/details/115670973如下:我们点击一个按钮开启线程,然后点击取消按钮取消该线程的执行    CancellationTokenSourcect......
  • C#任务取消--CancellationTokenSource取消令牌源
    一、概述在讲任务取消之前,得先了解取消令牌跟取消令牌源,实现任务取消功能的就是依靠这两个。CancellationTokenSource:取消令牌源类,拥有Cancel()方法,可以给关联的令牌......