Question

There are several extension methods for example, on the ConcurrentDictionary class, because it implements the IEnumerable interface. Are these methods (for example First, Sum, Take, etc.) are inherently thread-safe or not?

Was it helpful?

Solution

The extension methods don't add or remove any thread-safety. But you can't really ignore that iterating a collection is never thread-safe, whether you do it explicitly or let Linq do it. You must ensure that no other thread can modify the collection at the same time.

Beware that this is extra tricky in Linq because of its delayed execution behavior.

OTHER TIPS

The Linq-To-Objects Extension methods are implemented as static methods on System.Linq.Enumerable, and MSDN states they are all thread safe:

Any public static (Shared in Visual Basic) members of this type are thread safe

If you are using them with thread safe parameters (which ConcurrentDictionary is), you should not have any problems.

Now you can use advance Concurrent collection that are introduce in .Net 4.0 that are thread safe. This is really awesome concept. No need to manage lock or anything.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top