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:
Queue.Synchronized
is different than ConcurrentQueue<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 in System.Collections
are 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With