What thread-safe collection is appropriate for this scenario?

旧街凉风 提交于 2019-12-25 06:54:59

问题


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.

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.


回答1:


I think you should stick with ConcurrentDictionary ...




回答2:


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



来源:https://stackoverflow.com/questions/7895766/what-thread-safe-collection-is-appropriate-for-this-scenario

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!