IEnumerable T线程安全? [英] IEnumerable<T> thread safety?

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

问题描述

我有一个填充List<T>的主线程.此外,我创建了一个将在不同线程上执行的对象链,需要访问List.原始列表生成后将永远不会写入.我的想法是将列表作为IEnumerable<T>传递给在其他线程上执行的对象,主要是因为不允许那些实现那些对象的对象错误地写入列表.换句话说,如果保证不写入原始列表,那么多个线程在IEnumerable上使用.Whereforeach是否安全?

I have a main thread that populates a List<T>. Further I create a chain of objects that will execute on different threads, requiring access to the List. The original list will never be written to after it's generated. My thought was to pass the list as IEnumerable<T> to the objects executing on other threads, mainly for the reason of not allowing those implementing those objects to write to the list by mistake. In other words if the original list is guaranteed not be written to, is it safe for multiple threads to use .Where or foreach on the IEnumerable?

如果原始集合从未更改,我不确定迭代器本身是否是线程安全的.

I am not sure if the iterator in itself is thread safe if the original collection is never changed.

推荐答案

IEnumerable<T>无法修改.那么,非线程安全又有什么用呢? (如果您不修改实际的List<T>).

IEnumerable<T> can't be modified. So what can be non thread safe with it? (If you don't modify the actual List<T>).

为了非线程安全,您需要进行读写操作.

For non thread safety you need writing and reading operations.

为每个foreach实例化自身的迭代器".

"Iterator in itself" is instantiated for each foreach.

编辑:我简化了回答,但@Eric Lippert添加了宝贵的评论. IEnumerable<T>没有定义修改方法,但这并不意味着访问运算符是线程安全的(GetEnumeratorMoveNext等).最简单的示例:GetEnumerator如此实现:

I simplified my answer a bit, but @Eric Lippert added valuable comment. IEnumerable<T> doesn't define modifying methods, but it doesn't mean that access operators are thread safe (GetEnumerator, MoveNext and etc.) Simplest example: GetEnumerator implemented as this:

  • 每次返回IEnumerator的相同实例
  • 重置位置
  • Every time returns same instance of IEnumerator
  • Resets it's position

更复杂的示例是缓存.

这很有趣,但是幸运的是,我不知道任何没有IEnumerable线程安全实现的标准类.

This is interesting point, but fortunately I don't know any standard class that has not thread-safe implementation of IEnumerable.

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

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