什么线程安全收集适合这种情况? [英] What thread-safe collection is appropriate for this scenario?

查看:148
本文介绍了什么线程安全收集适合这种情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单例类处理来自不同线程中运行的不同客户端的订阅和取消订阅请求。单例包含订阅者的集合。在添加或删除之前,该类需要验证元素是否尚未添加或删除。

I have a singleton class handling Subscribe and Unsubscribe requests from different clients running in different threads. The singleton contains a collection of Subscribers. Before adding or removing, the class needs to validate that the element hasn't already been added or deleted.

通常我会使用List或HashSet调用实现在每个操作之前,但如果我想使用System.Collections.Concurrent命名空间中的一个新类,我看到的唯一选项是使用一个虚拟值的ConcurrentDictionary。

Normally I would implement this using a List or a HashSet calling Contains before each operation, but if I want to use one of the new classes in the System.Collections.Concurrent namespace, the only option I see is to use a ConcurrentDictionary with a dummy value.

这是我最好的选择还是有什么我忽略?顺便说一句,性能不是真正的考虑因素。

Is this my best option or is there something I'm overlooking? By the way, performance is not really a factor to consider.

推荐答案

为什么不使用ConcurrentDictionary支持阻塞队列。 BlockingQueue似乎适合您的生产者/消费者方案,ConcurrentDictionary适合您的查找。

Why dont you use ConcurrentDictionary backed with Blocking Queue. BlockingQueue seems to fit your producer/consumer scheme, and ConcurrentDictionary for your lookups.

这篇关于什么线程安全收集适合这种情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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