What thread-safe collection in the .Net Framework has Contains as one of its APIs?

I know that ConcurrentDictionary has an API called ContainsKey, but the dictionary is not what I'm looking for. Right now I'm using the "Contains" extension method from Enumerable, but this method is not thread safe. So, is there a thread-safe collection that has a Contains method?

Thanks.

+4
source share
1 answer

In general, the Contains operation is not very useful in a parallel collection. The problem is that as soon as you define the collection β€œcontains” or does not contain any object, the logic that you perform as a result of this check is no longer valid, since another thread can add or remove an element immediately after.

The ConcurrentDictionary class contains this method for implementing IDictionary, but the intended use should actually use AddOrUpdate , GetOrAdd and similar atomic methods.

+15
source

Source: https://habr.com/ru/post/1347652/


All Articles