并发集合和唯一元素 [英] Concurrent Collections and Unique elements

查看:72
本文介绍了并发集合和唯一元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有重复元素的并发 BlockingCollection.如何修改它以添加或获取不同的元素?

I have a concurrent BlockingCollection with repeated elements. How can modify it to add or get distinct elements?

推荐答案

BlockingCollection 的默认后备存储是 ConcurrentQueue.正如其他人指出的那样,使用它添加不同的项目相当困难.

The default backing store for BlockingCollection is a ConcurrentQueue. As somebody else pointed out, it's rather difficult to add distinct items using that.

但是,您可以创建自己的集合类型来实现 IProducerConsumerCollection,并将其传递给 BlockingCollection 构造函数.

However, you could create your own collection type that implements IProducerConsumerCollection, and pass that to the BlockingCollection constructor.

想象一个 ConcurrentDictionary 包含当前在队列中的项目的键.要添加一个项目,您首先在字典上调用 TryAdd,如果该项目不在字典中,则添加它,并将其添加到队列中.Take(和 TryTake)从队列中获取下一项,从字典中删除它,然后返回.

Imagine a ConcurrentDictionary that contains the keys of the items that are currently in the queue. 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. Take (and TryTake) get the next item from the queue, remove it from the dictionary, and return.

如果有并发 HashTable,我更喜欢,但由于没有,你必须使用 ConcurrentDictionary.

I'd prefer if there was a concurrent HashTable, but since there isn't one, you'll have to do with ConcurrentDictionary.

这篇关于并发集合和唯一元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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