System.Collections.Queue class has Queue.Synchronized method which returns a thread-safe Queue implementation.
But the generic one, System.Collections.Generic.Queue does not have a Synchronized method. At this point I have two questions in mind:
- Why doesn’t generic one have this method? Is it a framework API design decision?
- How is the queue returned from
Queue.Synchronizedis different thanConcurrentQueue<T>class?
Thanks.
The
Synchronized()method returns a wrapper queue that slaps a lock around every method.This pattern is not actually useful when writing multi-threaded applications.
Most real-world use patterns will not benefit for a synchronized collections; they will still need locks around higher-level operations.
Therefore, the
Synchronized()methods inSystem.Collectionsare actually a trap that lead people into writing non-thread-safe code.The
ConcurrentQueue<T>class is specifically designed for concurrent applications and contains useful methods that atomically modify the queue.The concurrent collections package only contain methods that make sense to use in a multi-threaded environment (eg,
TryDequeue()); they will help guide you to write code that is actually thread-safe.This is called the pit of success.
For much more information, see my blog