简体   繁体   English

并发集合和独特元素

[英]Concurrent Collections and Unique elements

I have a concurrent BlockingCollection with repeated elements. 我有一个带有重复元素的并发BlockingCollection How can modify it to add or get distinct elements? 如何修改它以添加或获取不同的元素?

The default backing store for BlockingCollection is a ConcurrentQueue . BlockingCollection的默认后备存储是ConcurrentQueue As somebody else pointed out, it's rather difficult to add distinct items using that. 正如其他人所指出的那样,使用它添加不同的项目相当困难。

However, you could create your own collection type that implements IProducerConsumerCollection , and pass that to the BlockingCollection constructor. 但是,您可以创建自己的集合类型来实现IProducerConsumerCollection ,并将其传递给BlockingCollection构造函数。

Imagine a ConcurrentDictionary that contains the keys of the items that are currently in the queue. 想象一下ConcurrentDictionary ,它包含当前队列中项目的键。 To add an item, you call TryAdd on the dictionary first, and if the item isn't in the dictionary you add it, and also add it to the queue. 要添加项目,首先在字典上调用TryAdd ,如果项目不在字典中,则添加项目,并将其添加到队列中。 Take (and TryTake ) get the next item from the queue, remove it from the dictionary, and return. Take (和TryTake )从队列中获取下一个项目,将其从字典中删除,然后返回。

I'd prefer if there was a concurrent HashTable , but since there isn't one, you'll have to do with ConcurrentDictionary . 我更喜欢并发HashTable ,但由于没有HashTable ,你将不得不使用ConcurrentDictionary

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM