CancellationToken取消不会破坏BlockingCollection

我有这样的取消令牌

static CancellationTokenSource TokenSource= new CancellationTokenSource(); 

我有一个像这样的阻止集合

 BlockingCollection items= new BlockingCollection(); var item = items.Take(TokenSource.Token); if(TokenSource.CancelPending) return; 

我打电话的时候

 TokenSource.Cancel(); 

Take不会像它应该的那样继续下去。 如果我使用带轮询的TryTake,令牌显示它被设置为已取消。

这是按预期工作的。 如果操作被取消, items.Take将抛出OperationCanceledException 。 此代码说明了这一点:

 static void DoIt() { BlockingCollection items = new BlockingCollection(); 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(); }