IEnumerable thread safety?

后端 未结 6 1245
我在风中等你
我在风中等你 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:21

    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?

    Yes it's only a problem if the list gets mutated.

    But note than IEnumerable can be cast back to a list and then modified.

    But there is another alternative: wrap your list into a ReadOnlyCollection and pass that around. If you now throw away the original list you basically created a new immutable list.

提交回复
热议问题