Are IEnumerable Linq methods thread-safe?

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

Solution 1:

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.

Solution 2:

In short, they are not thread safe as mentioned above.

However, that does not mean you must lock before "every sort of iteration."

You need to synchronize all operations that change the collection (add, modify, or remove elements) with other operations that (add, modify, remove elements, or read elements).

If you are only performing read operations on the collection concurrently, no locking is needed. (so running LINQ commands like Average, Contains, ElementAtOrDefault all together would be fine)

If the elements in the collection are of machine word length, such as Int on most 32-bit computers, then changing the value of that element is already performed atomically. In this case don't add or remove elements from the collection without locking, but modifying values may be okay, if you can deal with some non-determinism in your design.

Lastly, you can consider fine-grained locking on individual elements or sections of the collection, rather than locking the entire collection.