Zsolt
Zsolt

Reputation: 3283

Extension methods on System.Collections.Concurrent collections are thread-safe?

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?

Upvotes: 3

Views: 830

Answers (3)

Nilesh Moradiya
Nilesh Moradiya

Reputation: 31

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.

Upvotes: -1

Hans Passant
Hans Passant

Reputation: 941495

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.

Upvotes: 3

Botz3000
Botz3000

Reputation: 39610

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.

Upvotes: 0

Related Questions