13

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.

Barry
  • 3,303
  • 7
  • 23
  • 42
AncientSyntax
  • 919
  • 8
  • 12
  • 3
    Where is the thread? – leppie Dec 19 '14 at 16:09
  • You might have this in an asp.net app and multiple threads will access it without you creating them manually – pollirrata Dec 19 '14 at 16:10
  • 1
    There's no multi threading in your code but if you are in a multithreaded environment the ConcurrentQueue is definitely the good type to use because it provides thead safe access to your Queue.. – FloChanz Dec 19 '14 at 16:14
  • 1
    @pollirrata, that is not relevant when the data structure in question is created right then and there and evidently not accessible to other threads. – Kirk Woll Dec 19 '14 at 16:14
  • Modifying the queue inside tasks is pointless unless it's meant as a sample. These operations take minimal time and there's no point in running them in the background. – Panagiotis Kanavos Dec 19 '14 at 16:18
  • I would imagine they are. The Any() extension method will most likely work on the enumerator returned by the collection. This enumerator is thread safe (uses spin locks and locks) for ConcurrentQueue which should in turn make the linq extension itself thread safe. – kha Dec 19 '14 at 16:19
  • The LINQ [`ToArray`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.toarray) is not safe to use with concurrent collections. See [this](https://stackoverflow.com/questions/29648849/net-concurrentdictionary-toarray-argumentexception ".NET ConcurrentDictionary.ToArray() ArgumentException") question. – Theodor Zoulias Feb 03 '23 at 20:19

3 Answers3

14

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.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • Thanks, that is what I was after. So if I wish to make LINQ operations and collection modifications mutually exclusive then I must implement my own locking collection. – AncientSyntax Dec 19 '14 at 16:19
  • That depends. It can be useful for example to wrap a queue in a blocking collection and the expose the dequeueing as an enumerable. You can then do linq operations on that but only block when the queue is empty. Or indeed not block at all but do something else and then later come back and repeat the linq operations. This would be concurrently modifying and doing linq stuff, without locking and with full thread-safety. – Jon Hanna Dec 19 '14 at 16:31
  • So that means that a lock is needed to avoid that the snapshot contains stale data on a longer LINQ query? You're still vulnerable to multithreading issues otherwise. – Tim Schmelter Oct 18 '16 at 08:14
4

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.

Jon Hanna
  • 110,372
  • 10
  • 146
  • 251
2

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.

pollirrata
  • 5,188
  • 2
  • 32
  • 50
  • 1
    [This documentation](http://msdn.microsoft.com/en-us/library/dd287144%28v=vs.110%29.aspx) would be more useful as it specifically talks about the method call on the collection that LINQ will use. – Rawling Dec 19 '14 at 16:27