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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With