Why doesn't Collections.Generic.Queue have a synchronized method, but Collections.Queue has one?

System.Collections.Queue class has a Queue.Synchronized method that returns a stream implementation of Queue.

But overall, System.Collections.Generic.Queue does not have a Synchronized method. At the moment, I have two questions:

Thanks.

+6
source share
1 answer

The Synchronized() method returns a wrapper queue that locks the lock for each method.
This template is not very useful when writing multi-threaded applications.

Most use patterns in the real world will not be useful for synchronized collections; they will still need locks around higher-level operations.

Therefore, the Synchronized() methods in System.Collections are actually traps that force people to write unsafe code.


The ConcurrentQueue<T> class is specifically designed for concurrent applications and contains useful methods that atomically change the queue.

The parallel collection package contains only methods that make sense in a multi-threaded environment (for example, TryDequeue() ); they will help you write code that is actually thread safe.

This is called the core of success .

See my blog for more details.

+13
source

All Articles