【问题标题】:ConcurrentDictionary TryGetValue vs []. Is [] still thread-safe?并发字典 TryGetValue 与 []。 [] 仍然是线程安全的吗?
【发布时间】:2013-06-13 13:30:55
【问题描述】:

我有以下ConcurrentDictionary

ConcurrentDictionary<Guid, Session> sessions;

我知道sessions.TryGetValue(key, out session) 是线程安全的,但我的问题是sessions[key] 是否也是线程安全的?

sessions.TryGetValue(key, out session) 返回真或假取决于它是否能够获取值。

如果无法获取值,sessions[key] 会返回null 吗?我会这么认为。任何人都可以确认或阐明这一点吗?谢谢。

【问题讨论】:

    标签: .net c#-4.0 concurrentdictionary


    【解决方案1】:

    它是线程安全的,但不会返回null

    documentation 明确指出:

    例外情况

    KeyNotFoundException
    已检索到属性,但集合中不存在键。

    【讨论】:

    • 你能在文档中给我一个链接吗,我找不到它。谢谢!
    • 感谢您的快速回答!我看到它映射到Item 集合。现在这是有道理的。我之前不确定如何在文档中找到它。
    • @Chris:这个类的重点是线程安全的;所有操作都是原子的。文档明确声明All public and protected members of ConcurrentDictionary&lt;TKey, TValue&gt; are thread-safe and may be used concurrently from multiple threads. However, members accessed through one of the interfaces the ConcurrentDictionary&lt;TKey, TValue&gt; implements, including extension methods, are not guaranteed to be thread safe and may need to be synchronized by the caller.
    • @SLaks:因此,由于索引器属性TValue this[ TKey key ]IDictionary&lt;TKey, TValue&gt; 的实现,因此不能保证它是线程安全的。为什么说是?
    • @BlackOverlord:这表示“通过其中一个接口访问的成员”,而不是由接口定义的成员。换句话说,显式接口实现。
    猜你喜欢
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多