Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which thread-safe collection in the .Net Framework has a “Contains” as one of its API?

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.

like image 363
Cui Pengfei 崔鹏飞 Avatar asked Dec 07 '22 22:12

Cui Pengfei 崔鹏飞


1 Answers

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.

like image 139
Reed Copsey Avatar answered Jan 01 '23 03:01

Reed Copsey