IEnumerable thread safety?

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

    If you are certain that the list will not be modified after creation, you should guarantee that by converting it to a ReadOnlyCollection. Of course if you keep the original list that the read only collection uses you can modify it, but if you toss the original list away you're effectively making it permentantly read only.

    From the Thread Safety section of the collection:

    A ReadOnlyCollection can support multiple readers concurrently, as long as the collection is not modified.

    So if you don't touch the original list again and stop referencing it, you can ensure that multiple threads can read it without worry (so long as you don't do anything wacky with trying to modify it again).

提交回复
热议问题