Are IEnumerable Linq methods thread-safe?

前端 未结 2 1813
情书的邮戳
情书的邮戳 2020-11-28 13:11

I wonder if Linq extension methods are atomic? Or do I need to lock any IEnumerable object used across threads, before any sort of iteration?

2条回答
  •  误落风尘
    2020-11-28 14:07

    In short, they are not thread safe as mentioned above.

    However, that does not mean you must lock before "every sort of iteration."

    You need to synchronize all operations that change the collection (add, modify, or remove elements) with other operations that (add, modify, remove elements, or read elements).

    If you are only performing read operations on the collection concurrently, no locking is needed. (so running LINQ commands like Average, Contains, ElementAtOrDefault all together would be fine)

    If the elements in the collection are of machine word length, such as Int on most 32-bit computers, then changing the value of that element is already performed atomically. In this case don't add or remove elements from the collection without locking, but modifying values may be okay, if you can deal with some non-determinism in your design.

    Lastly, you can consider fine-grained locking on individual elements or sections of the collection, rather than locking the entire collection.

提交回复
热议问题