Synchronizing a Queue

  • Thread starter Thread starter Chuck
  • Start date Start date
C

Chuck

I have not been able to find a good answer about the
System.Collections.Queue.Synchronized() method and how it actually works or
is to be used.

If I create my Queue in the following manner:

System.Collections.Queue myQueue = System.Collections.Queue.Synchronized(new
System.Collections.Queue());

is it a Thread-Safe queue no matter where it is used? Or do I have to call
Synchronized() and use the Queue that it returns everytime I want to use the
Queue.

Thanks,
Chuck
 
The operations within myQueue will always be thread safe.

Be very careful what assumptions you make about using a synchronized
Queue. A synchronized collection simply means that each individual
method (Enqueue, Dequeue) is safe to call from multiple threads without,
damaging the internal state. But multiple calls to the methods are not
thread safe without additional coding.

For example, if you write the code:

if (myQueue.Count > 0){
item = myQueue.Dequeue()
}

it is still possible that you will get an InvalidOperationException when
multiple threads have access to myQueue. Another thread could remove
the last item in between the check on .Count and the actual Dequeue().
If you want the above code to work in a thread safe manner, you would
still need to use a locking mechanism.

For example:
lock(myQueue.SyncRoot){
if (myQueue.Count > 0){
item = myQueue.Dequeue()
}
}
 
Back
Top