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”开发者_如何学Go 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.
精彩评论