Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are IEnumerable Linq methods thread-safe?

Tags:

I wonder if Linq extension methods are atomic? Or do I need to lock any IEnumerable object used across threads, before any sort of iteration?

Does declaring the variable as volatile have any affect on this?

To sum up, which of the following is the best, thread safe, operation?

1- Without any locks:

IEnumerable<T> _objs = //... var foo = _objs.FirstOrDefault(t => // some condition 

2- Including lock statements:

IEnumerable<T> _objs = //... lock(_objs) {     var foo = _objs.FirstOrDefault(t => // some condition } 

3- Declaring variable as volatile:

volatile IEnumerable<T> _objs = //... var foo = _objs.FirstOrDefault(t => // some condition 
like image 409
Kamyar Nazeri Avatar asked Jun 19 '12 15:06

Kamyar Nazeri


People also ask

Can I use Linq with IEnumerable?

The IEnumerable<T> interface is central to LINQ. All LINQ methods are extension methods to the IEnumerable<T> interface. That means that you can call any LINQ method on any object that implements IEnumerable<T> .

What is thread safe in C#?

A piece of code or data structure is thread safe, when the outcome of the code and underlying resources do not create undesirable results (inconsistent data, exception etc.), because of multiple threads interacting with the code concurrently. That simply means: All threads behave properly.

Are enumerators thread safe?

However, the standard C# List<T> and Enumerator<T> are not thread-safe and we started seeing problems when the list is modified by one thread whilst another is trying to loop through it.


1 Answers

The interface IEnumerable<T> is not thread safe. See the documentation on http://msdn.microsoft.com/en-us/library/s793z9y2.aspx, which states:

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.

The enumerator does not have exclusive access to the collection; therefore, enumerating through a collection is intrinsically not a thread-safe procedure. To guarantee thread safety during enumeration, you can lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

Linq does not change any of this.

Locking can obviously be used to synchronize access to objects. You must lock the object everywhere you access it though, not just when iterating over it.

Declaring the collection as volatile will have no positive effect. It only results in a memory barrier before a read and after a write of the reference to the collection. It does not synchronize collection reading or writing.

like image 199
Kris Vandermotten Avatar answered Oct 13 '22 18:10

Kris Vandermotten