C# CancellationToken取消未中断BlockingCollection

C# CancellationToken取消未中断BlockingCollection,c#,collections,parallel-processing,cancellation-token,C#,Collections,Parallel Processing,Cancellation Token,我有一个这样的取消代币 static CancellationTokenSource TokenSource= new CancellationTokenSource(); 我有一个这样的收藏 BlockingCollection<object> items= new BlockingCollection<object>(); var item = items.Take(TokenSource.Token); if(TokenSource.CancelPend

我有一个这样的取消代币

   static CancellationTokenSource TokenSource= new CancellationTokenSource();
我有一个这样的收藏

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

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

if(TokenSource.CancelPending)
   return;

这种情况不会继续下去。如果我将TryTake与轮询一起使用,则令牌显示它被设置为已取消。

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

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();
}
静态void DoIt()
{
BlockingCollection项=新建BlockingCollection();
CancellationTokenSource src=新的CancellationTokenSource();
ThreadPool.QueueUserWorkItem((s)=>
{
WriteLine(“线程已启动。正在等待项目或取消”);
尝试
{
var x=items.Take(src.Token);
Console.WriteLine(“使操作成功”);
}
捕获(操作取消异常)
{
WriteLine(“Take操作已取消。IsCancellationRequested={0}”,src.IsCancellationRequested);
}
});
控制台.WriteLine(“按ENTER键取消等待”);
Console.ReadLine();
src.Cancel(假);
Console.WriteLine(“取消发送。完成后按Enter键”);
Console.ReadLine();
}
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();
}