Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
827 views
in Technique[技术] by (71.8m points)

c# - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...