If a Queue is syncronized:
var _item = Queue.Synchronized(new Queue());
can I call methods like Enqueue and Dequeue on it without using lock statements?
My current code is:
lock (_item.SyncRoot)
{
_item.Enqueue(obj);
}
Can I thread-safely use:
_item.Enqueue(obj);
var item = _item.Dequeue();
The call to
Enqueueand the call toDequeueare thread safe.However, your sample code is not:
Between the call to
Enqueueand the call toDequeuethere could have been a thread switch. This means, thatitemmight be another instance thanobjor the call toDequeuethrows an exception, because it now is empty.To make your sample code thread safe, you still need to lock explicitly:
Only now it is guaranteed, that
itemreference-equalsobjin all circumstances.