"are ienumerable linq methods thread-safe?" Code Answer


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.

By jglouie on July 19 2022

Answers related to “are ienumerable linq methods thread-safe?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.