如何从ConcurrentBag中删除单个特定对象? [英] How to remove a single, specific object from a ConcurrentBag<>?

查看:81
本文介绍了如何从ConcurrentBag中删除单个特定对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用.NET 4中新的 ConcurrentBag< T> ,当仅 TryTake() TryPeek时,如何从中删除特定对象()可用吗?

With the new ConcurrentBag<T> in .NET 4, how do you remove a certain, specific object from it when only TryTake() and TryPeek() are available?

我正在考虑使用 TryTake(),然后如果我不想想要删除它,则只是将结果对象重新添加到列表中,但是我觉得就像我可能会丢失一些东西.这是正确的方法吗?

I'm thinking of using TryTake() and then just adding the resulting object back into the list if I don't want to remove it, but I feel like I might be missing something. Is this the correct way?

推荐答案

简短的答案:您无法以简单的方式做到这一点.

The short answer: you can't do it in an easy way.

ConcurrentBag为每个线程保留一个线程本地队列,并且仅在其自己的队列为空时才查看其他线程的队列.如果您删除一个项目并将其放回原处,那么您删除的下一个项目可能又是同一项目.无法保证反复删除项目并将其放回原处将使您可以遍历所有项目.

The ConcurrentBag keeps a thread local queue for each thread and it only looks at other threads' queues once its own queue becomes empty. If you remove an item and put it back then the next item you remove may be the same item again. There is no guarantee that repeatedly removing items and putting them back will allow you to iterate over the all the items.

为您提供两种选择:

  • 删除所有项目并记住它们,直到找到要删除的项目,然后再将其他项目放回去.请注意,如果两个线程尝试同时执行此操作,则会遇到问题.
  • 使用更合适的数据结构,例如 ConcurrentDictionary .
  • li>

这篇关于如何从ConcurrentBag中删除单个特定对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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