IEnumerable Linq 方法线程安全吗? [英] Are IEnumerable Linq methods thread-safe?

查看:33
本文介绍了IEnumerable Linq 方法线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 Linq 扩展方法是否是原子的?或者我是否需要在任何类型的迭代之前lock任何跨线程使用的IEnumerable对象?

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?

将变量声明为 volatile 是否对此有任何影响?

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- 没有任何锁:

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

2- 包括锁定语句:

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

3- 将变量声明为 volatile:

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

推荐答案

IEnumerable 接口不是线程安全的.请参阅 http://msdn.microsoft.com/en-us/library 上的文档/s793z9y2.aspx,其中指出:

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 不会改变这些.

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.

将集合声明为 volatile 不会有任何积极影响.它只会在读取之前和写入对集合的引用之后产生内存屏障.它不同步集合读取或写入.

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.

这篇关于IEnumerable Linq 方法线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆