Are linq operations on concurrent collections thread safe?

核能气质少年 提交于 2019-12-30 17:45:23

问题


For example is the following code thread safe:

ConcurrentQueue<Guid> _queue = new ConcurrentQueue<Guid>();
while(true)
{
for(int y = 0; y < 3; y++)
{
    if(y % 3 == 0)
    {
    System.Threading.Tasks.Task.Run(() => _queue.Enqueue(Guid.NewGuid()));
    }
    else if (y % 3 == 1)
    {
    Guid x;
    System.Threading.Tasks.Task.Run(() => _queue.TryDequeue(out x));
    }
    else if(y % 3 == 2)
    {
    System.Threading.Tasks.Task.Run(() =>
    {
        if (_queue.Any(t => t == testGuid))
        {
        // Do something
        }
    });

    }
}

Edit: Apparently the title wasn't clear enough so updated the code sample to include actual multi threaded behaviour, yes the code above is just a sample of multi-threaded behaviour.


回答1:


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.




回答2:


Yes, but...

Let's take your example:

if(_queue.Any(t => t == testGuid))
{
     // Do something
}

Now this will not, no matter what other threads are doing, fail with an exception except in documented ways (which in this case means fail with any exception), put _queue into an invalid state, or return an incorrect answer.

It is, as such, thread-safe.

Now what?

Your code at // Do something presumably is only to be done if there's an element in the queue that matches testGuid. Unfortunately we don't know if this is true or not, because the Heraclitan stream of time has moved on, and all we know is that there was such a Guid in there.

Now, this isn't necessarily useless. We could for example know that the queue is currently only being added to (maybe the current thread is the only one that dequeues for example, or all dequeueing happens under certain conditions that we know are not in place). Then we know that there is still such a guid in there. Or we could just want to flag that testGuid was seen whether it's still there or not.

But if // Do something depends on the presence of testGuid in the queue, and the queue is being dequeued from, then the code-block as a whole is not thread-safe, though the link expression is.




回答3:


Yes, according to documentation

The System.Collections.Concurrent namespace provides several thread-safe collection classes that should be used in place of the corresponding types in the System.Collections and System.Collections.Generic namespaces whenever multiple threads are accessing the collection concurrently.



来源:https://stackoverflow.com/questions/27569747/are-linq-operations-on-concurrent-collections-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!