Why doesn't Collections.Generic.Queue have Synchronized method but Collections.Queue has?

纵饮孤独 提交于 2019-12-22 05:53:18

问题


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:

  1. Why doesn't generic one have this method? Is it a framework API design decision?
  2. How is the queue returned from Queue.Synchronized is different than ConcurrentQueue<T> class?

Thanks.


回答1:


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



来源:https://stackoverflow.com/questions/14148938/why-doesnt-collections-generic-queue-have-synchronized-method-but-collections-q

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!