为什么不Collections.Generic.Queue有同步的方法,但Collections.Queue了? [英] Why doesn't Collections.Generic.Queue have Synchronized method but Collections.Queue has?

查看:317
本文介绍了为什么不Collections.Generic.Queue有同步的方法,但Collections.Queue了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

System.Collections.Queue 类具有的 Queue.Synchronized 方法返回一个线程安全的Queue实现。

System.Collections.Queue class has Queue.Synchronized method which returns a thread-safe Queue implementation.

但一般之一, System.Collections.Generic.Queue 不具有同步方法。在这一点上我心里有两个问题:

But the generic one, System.Collections.Generic.Queue does not have a Synchronized method. At this point I have two questions in mind:


  1. 为什么不通用的人不得不这种方法吗?它是一个框架,API设计决定吗?

  2. 如何从的 Queue.Synchronized 比的 ConcurrentQueue< T>

  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?

感谢。

推荐答案

同步()方法返回一个掴周围的每一个方法的锁的包装队列。结果
这个模式是不是编写多线程应用程序时,实际的用处。

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.

因此,<$ c中的同步()方法$ C> System.Collections中实际上是引领人们进入写非线程安全的代码陷阱。

Therefore, the Synchronized() methods in System.Collections are actually a trap that lead people into writing non-thread-safe code.

ConcurrentQueue< T> 类是专为并行应用而设计的,并包含有用的方法是原子修改队列

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

并发集合包只包含意义的在多线程环境中使用的方法(例如, TryDequeue());他们会帮助引导你编写代码,实际上是线程安全的。

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.

这就是所谓的的成功的坑。

有关多更多信息,请参见我的博客

For much more information, see my blog

这篇关于为什么不Collections.Generic.Queue有同步的方法,但Collections.Queue了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆