问题
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