CancellationTokenSource

 

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

 

posted @ 2022-11-14 00:02  ProZkb  阅读(29)  评论(0编辑  收藏  举报