一尘不染

实现线程安全字典的最佳方法是什么?

c#

通过从IDictionary派生并定义私有SyncRoot对象,我能够在C#中实现线程安全的Dictionary:

public class SafeDictionary<TKey, TValue>: IDictionary<TKey, TValue>
{
    private readonly object syncRoot = new object();
    private Dictionary<TKey, TValue> d = new Dictionary<TKey, TValue>();

    public object SyncRoot
    {
        get { return syncRoot; }
    }

    public void Add(TKey key, TValue value)
    {
        lock (syncRoot)
        {
            d.Add(key, value);
        }
    }

    // more IDictionary members...
}

然后,在整个使用者(多个线程)上锁定此SyncRoot对象:

例:

lock (m_MySharedDictionary.SyncRoot)
{
    m_MySharedDictionary.Add(...);
}

我能够使其工作,但这导致了一些难看的代码。我的问题是,是否有更好,更优雅的方法来实现线程安全字典?


阅读 377

收藏
2020-05-19

共1个答案

一尘不染

如Peter所说,您可以将所有线程安全性封装在类中。您需要谨慎处理任何公开或添加的事件,以确保它们在任何锁之外都被调用。

public class SafeDictionary<TKey, TValue>: IDictionary<TKey, TValue>
{
    private readonly object syncRoot = new object();
    private Dictionary<TKey, TValue> d = new Dictionary<TKey, TValue>();

    public void Add(TKey key, TValue value)
    {
        lock (syncRoot)
        {
            d.Add(key, value);
        }
        OnItemAdded(EventArgs.Empty);
    }

    public event EventHandler ItemAdded;

    protected virtual void OnItemAdded(EventArgs e)
    {
        EventHandler handler = ItemAdded;
        if (handler != null)
            handler(this, e);
    }

    // more IDictionary members...
}

Edit: The MSDN docs point out that enumerating is inherently not thread
safe. That can be one reason for exposing a synchronization object outside
your class. Another way to approach that would be to provide some methods for
performing an action on all members and lock around the enumerating of the
members. The problem with this is that you don’t know if the action passed to
that function calls some member of your dictionary (that would result in a
deadlock). Exposing the synchronization object allows the consumer to make
those decisions and doesn’t hide the deadlock inside your class.

2020-05-19