I know ConcurrentDictionary has an API called ContainsKey, but a dictionary is not what I’m looking for. For now, I am using the “Contains” extension method from Enumerable, but that method is not thread-safe. So is there any thread-safe collection that has a “Contains” method?
Thanks.
In general, a Contains
operation is not very useful in a concurrent collection. The problem is that, as soon as you determine the collection "contains" or doesn't contain some object, the logic you do as a result of that check is no longer valid, as another thread may have added or removed the item immediately following.
The ConcurrentDictionary class contains this method to implement IDictionary, but the intended usage is actually to use AddOrUpdate
, GetOrAdd
, and the similar atomic methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With