gpt4 book ai didi

c# - IEnumerable Linq 方法是线程安全的吗?

转载 作者:IT王子 更新时间:2023-10-29 04:38:23 25 4
gpt4 key购买 nike

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

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

总而言之,以下哪项是最好的线程安全操作?

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<T>不是线程安全的。请参阅 http://msdn.microsoft.com/en-us/library/s793z9y2.aspx 上的文档,其中指出:

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 不会改变任何这些。

显然可以使用锁定来同步对对象的访问。但是,您必须在访问它的任何地方锁定该对象,而不仅仅是在迭代它时。

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

关于c# - IEnumerable Linq 方法是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11103779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com