CancellationToken Cancel not breaking out of BlockingCollection

前端 未结 1 1658
余生分开走
余生分开走 2021-01-11 09:26

I have a cancellation token like so

   static CancellationTokenSource TokenSource= new CancellationTokenSource();

I have a blocking collect

相关标签:
1条回答
  • 2021-01-11 10:08

    That's working as expected. If the operation is canceled, items.Take will throw OperationCanceledException. This code illustrates it:

    static void DoIt()
    {
        BlockingCollection<int> items = new BlockingCollection<int>();
        CancellationTokenSource src = new CancellationTokenSource();
        ThreadPool.QueueUserWorkItem((s) =>
            {
                Console.WriteLine("Thread started. Waiting for item or cancel.");
                try
                {
                    var x = items.Take(src.Token);
                    Console.WriteLine("Take operation successful.");
                }
                catch (OperationCanceledException)
                {
                    Console.WriteLine("Take operation was canceled. IsCancellationRequested={0}", src.IsCancellationRequested);
                }
            });
        Console.WriteLine("Press ENTER to cancel wait.");
        Console.ReadLine();
        src.Cancel(false);
        Console.WriteLine("Cancel sent. Press Enter when done.");
        Console.ReadLine();
    }
    
    0 讨论(0)
提交回复
热议问题