CancellationToken取消不突破BlockingCollection

编程入门 行业动态 更新时间:2024-10-26 10:26:46
本文介绍了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

本文发布于:2023-11-12 21:41:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582600.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:CancellationToken   BlockingCollection

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!