如何创建不重复的ConcurrentQueue?
我需要一个不允许重复的并发集合(在 BlockingCollection 中作为生产者/消费者使用)。 我不需要严格的元素顺序。 另一方面,我想最小化元素在集合中“存活”的最长时间。即收集不能是后进先出的,理想情况下应该是先进先出的。
好吧,我会说我需要不允许重复的 ConcurrentQueue
,但是不允许重复的 ConcurrentBag
也可能有效。
为什么 C# 不包含类似的东西并且可能已经有人创建了它?
这个问题是我上一个问题 什么类型的 IProducerConsumerCollection
I need a concurrent collection that doesn't allow duplicates (to use in BlockingCollection
as Producer/Consumer).
I don't need strict order of elements.
From another hand i want to minimize the maximum time of element "live" in collection. I.e. collection mustn't be LIFO, ideally it should be FIFO.
Well I would say that I need ConcurrentQueue
with no duplicates allowed, but ConcurrentBag
with no duplicates also might work.
Why C# doesn't contain anything like that and probably someone already created it?
This question is result of my previous question What type of IProducerConsumerCollection<T> to use for my task?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没有内置的 .Net 库可以将这组规则组合到一个集合中。您有以下三种选择:
最后两个效率不高(一个使用内存,另一个使用 CPU、I/O、锁定)并且比较混乱因为需要显式锁定,但可以完成任务。它们的实施速度会更快,但如果权衡不能满足您的要求,您将不得不选择选项#1。
There are no built-in .Net libraries that combine this set of rules for a collection. You have three options:
The last two aren't very efficient (one with memory, the other with CPU, I/O, locking) and are messier because of the need for explicit locking, but would accomplish the task. They will be quicker to implement, but if the trade-offs don't meet your requirements you'll have to go with option #1.
好吧,如果您严格希望没有重复项,则需要“集合”。例如,NHibernate 使用 Iesi.Collections 来提供此类功能。使用 Iesi,您可以围绕提供的“Set”类(DictionarySet、HashSet、SortedSet)构建您自己的功能。来源:http://www.codeproject.com/KB/recipes/sets.aspx
Well if you strictly want to have no duplicates, you need 'Sets'. For instance NHibernate uses Iesi.Collections to provide such functionality. Taking Iesi, you can build your own functionality around the provided 'Set' classes (DictionarySet, HashSet, SortedSet). Source: http://www.codeproject.com/KB/recipes/sets.aspx
您可以简单地使用
ConcurrentQueue
并在调用Enqueue
之前通过调用ConcurrentQueue.Contains
方法检查数据是否在队列中。我猜测Contains
扩展方法已经得到了相当好的优化。编辑:
正如其他人所指出的,要实现此目的,您必须在
Contains
方法和Enqueue
方法周围使用锁定机制,例如互斥体等像这样:You could simply use a
ConcurrentQueue
and before callingEnqueue
check if the data is in the queue by calling theConcurrentQueue.Contains<>
method. I'm guessing theContains<>
extension method is fairly well optimized.EDIT:
As others have noted, for this to work it would you'd have to use a locking mechanism such as a mutex etc around the
Contains<>
method and theEnqueue
method like this: