Are linq operations on concurrent collections thread safe?

后端 未结 3 1686
忘掉有多难
忘掉有多难 2021-01-17 23:28

For example is the following code thread safe:

ConcurrentQueue _queue = new ConcurrentQueue();
while(true)
{
for(int y = 0; y < 3;         


        
3条回答
  •  时光取名叫无心
    2021-01-18 00:03

    LINQ operations are read-only so they are thread safe on all collections. Of course, if you add code that modifies a collection inside the Where or Select method, they cease to be thread-safe.

    Thread-safe collections ensure that modifications are thread-safe, which isn't really a concern when executing a LINQ query.

    What isn't safe is modifying a collection during traversal. Normal collections invalidate iterators when they are modified, while the thread-safe collections do not. In some cases, (eg in ConcurrentQueue) this is achieved by presenting a snapshot of the data during iteration.

提交回复
热议问题