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

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

问题描述

我不知道是否LINQ的扩展方法是原子?或者,我需要锁定跨线程使用的任何的IEnumerable 对象,任何类型的迭代过吗?

请问声明变量为挥发性对此有何影响?

要总结起来,以下哪些是最好的,线程安全,操作?

1在没有任何锁:

 的IEnumerable< T> _objs = // ...
无功富= _objs.FirstOrDefault(T => //一些条件

2 - 包括锁语句:

 的IEnumerable< T> _objs = // ...
锁定(_objs)
{
    无功富= _objs.FirstOrDefault(T => //一些条件
}

3变量声明为volatile:

 挥发性的IEnumerable< T> _objs = // ...
无功富= _objs.FirstOrDefault(T => //一些条件


解决方案

接口的IEnumerable&LT; T&GT; 不是线程安全的。请参阅<一个文档href=\"http://msdn.microsoft.com/en-us/library/s793z9y2.aspx\">http://msdn.microsoft.com/en-us/library/s793z9y2.aspx,其中规定:


  

这是枚举仍然只要集合保持不变,有效。如果改变对集合进行,如添加,修改或删除元素,枚举数将失效且不可恢复,而且其行为是不确定的。


  
  

枚举数没有对集合的独占访问;因此,通过集合枚举是本质上不是一个线程安全的过程。要枚举过程中保证线程安全,可以在整个枚举过程中锁定集合。要允许由多个线程进行读取和写入访问的集合,您必须实现自己的同步。


LINQ的不改变任何这一点。

锁定显然可以用来同步访问对象。你必须处处锁定对象访问它虽然,在它迭代不只是当。

声明收集挥发性不会有任何积极的作用。它只是导致读取之前内存屏障和参考集合的写入后。它不会同步采集读取或写入。

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 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.

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

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