Are linq operations on concurrent collections thread safe?

后端 未结 3 1657
忘掉有多难
忘掉有多难 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-17 23:55

    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.

提交回复
热议问题