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
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> .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With