CancellationToken取消不突破BlockingCollection [英] CancellationToken Cancel not breaking out of BlockingCollection

查看:187
本文介绍了CancellationToken取消不突破BlockingCollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的取消令牌

   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;

当我打电话

TokenSource.Cancel();

汇整未如预期那样继续进行.如果我将TryTake与民意调查一起使用,则令牌会显示该令牌已设置为已取消".

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.

推荐答案

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

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

这篇关于CancellationToken取消不突破BlockingCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆