Reading the MSDN documentation on the Synchronized property on the Queue object I was left confused when reading the description. When working with queues and accessing them from multiple threads should I rely on the wrapped queue returned from the Synchronised method:
To guarantee the thread safety of the Queue, all operations must be done through the wrapper returned by the Synchronized method.
or should I play it safe and do lock the queue myself:
Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.
After discussing this and reading a few posts on the subject it seems that the confusion is around what an operation is in the first quote. It would seem that if I called the
dequeue method (read operation) on the Queue object that by default it is not thread safe. Calling the
dequeuemethond through the wrapper returned by the
synchronized method is thread safe.
So the next scenario is where you want two (2) or more calls on a queue to be thread safe as per the example for the syncrootproperty on MSDN. Here you need to manually lock the object in question.
For Each item In myCollection
' Insert your code here.