IEnumerable thread safety?

后端 未结 6 1246
我在风中等你
我在风中等你 2021-02-05 13:37

I have a main thread that populates a List. Further I create a chain of objects that will execute on different threads, requiring access to the List. The

6条回答
  •  长情又很酷
    2021-02-05 14:40

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

    For non thread safety you need writing and reading operations.

    "Iterator in itself" is instantiated for each foreach.

    Edit: I simplified my answer a bit, but @Eric Lippert added valuable comment. IEnumerable 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:

    • Every time returns same instance of IEnumerator
    • Resets it's position

    More sophisticated example is caching.

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

提交回复
热议问题