【问题标题】:Will Concurrent Dictionary holding thread unsafe collections require locks in C#持有线程不安全集合的并发字典是否需要 C# 中的锁
【发布时间】:2014-08-07 12:14:06
【问题描述】:

我声明 ConcurrentDictionary 如下

我担心的是,ConcurrentDictionary 是线程安全的,但 List 不是线程安全的。当我尝试使用钥匙访问此列表时,我是否必须在使用之前放置锁?还是 ConcurrentDictionary 会处理它?

任何细节,将不胜感激。

【问题讨论】:

    标签: c# .net multithreading collections concurrency


    【解决方案1】:

    ConcurrentDictionary 只会处理对字典的并发访问。任何在列表中引起副作用的代码,例如迭代它或添加值都必须附带额外的锁定机制,因为ConcurrentDictionary 不对此负责。

    所以是的,你必须在列表周围添加一个锁定机制,或者简单地使用ConcurrentBag<T>

    public static ConcurrentDictionary<int, ConcurrentBag<object>>
    

    【讨论】:

    • 感谢您的准确回答
    猜你喜欢
    • 2021-12-19
    • 2013-12-07
    • 1970-01-01
    • 2012-05-27
    • 2021-07-10
    • 2014-02-25
    • 2016-05-08
    • 2010-11-06
    相关资源
    最近更新 更多