CancellationToken Cancel not breaking out of BlockingCollection

Kenoyer130 picture Kenoyer130 · Apr 22, 2011 · Viewed 8.4k times · Source

I have a cancellation token like so

   static CancellationTokenSource TokenSource= new CancellationTokenSource();

I have a blocking collection like so

BlockingCollection<object> items= new BlockingCollection<object>();

var item = items.Take(TokenSource.Token);

if(TokenSource.CancelPending)
   return;

When I call

TokenSource.Cancel();

The Take does not continue like it should. If I use the TryTake with a poll the Token shows it is being set as Canceled.

Answer

Jim Mischel picture Jim Mischel · Apr 22, 2011

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