Do I still need to LOCK a Synchronized Queue?
-
if I do this:
Queue SynchedMessageQueue = Queue.Synchronized(new Queue());
then when I access SynchedMessageQueue, do I still need to use LOCK statements? Or is that now being handled automatically?
I believe that this answers the question (from MSDN Queue.Synchronized Method[^]):
To guarantee the thread safety of the Queue, all operations must be done through this wrapper only.
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.Mika
-
I believe that this answers the question (from MSDN Queue.Synchronized Method[^]):
To guarantee the thread safety of the Queue, all operations must be done through this wrapper only.
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.Mika
-
Thanks. I had read this, but for some reason I cannot now remember, I questioned it. Seems pretty straightforward now!
-
You're welcome. Mika P.s. Really glad to hear that you thought about this instead if just asking :)
I think what I blew off was that SPEFICICALLY, enumeration wasn't thread safe. In my mind I thought "well, if getting things from a synchronized queue isn't thread safe, what's the point?" My brain didn't translate the part where "Only the enumeration itself needs LOCK, the rest of the Queue methods do not."