8
实现线程安全字典的最佳方法是什么?
通过从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 …