ConcurrentDictionary是线程安全类,是什么在保证?
内部类
private class Tables { internal readonly Node[] m_buckets; // A singly-linked list for each bucket. internal readonly object[] m_locks // A set of locks, each guarding a section of the table. …… }
构造函数
internal ConcurrentDictionary(int concurrencyLevel, int capacity, bool growLockArray, IEqualityComparer<TKey> comparer) { if (concurrencyLevel < 1) { throw new ArgumentOutOfRangeException("concurrencyLevel", GetResource("ConcurrentDictionary_ConcurrencyLevelMustBePositive")); } if (capacity < 0) { throw new ArgumentOutOfRangeException("capacity", GetResource("ConcurrentDictionary_CapacityMustNotBeNegative")); } if (comparer == null) throw new ArgumentNullException("comparer"); // The capacity should be at least as large as the concurrency level. Otherwise, we would have locks that don't guard // any buckets. if (capacity < concurrencyLevel) { capacity = concurrencyLevel; } object[] locks = new object[concurrencyLevel]; for (int i = 0; i < locks.Length; i++) { locks[i] = new object(); } int[] countPerLock = new int[locks.Length]; Node[] buckets = new Node[capacity]; m_tables = new Tables(buckets, locks, countPerLock, comparer);
…… }
TryAdd内部实现
……
Monitor.Enter(tables.m_locks[lockNo], ref lockTaken);
……
Monitor.Exit(tables.m_locks[lockNo]);
……
实质是维护了一个tables,m_buckets 负责存储,m_locks负责保存锁。至于用哪个bucket,用哪个lock,是有一定的算法,和hash有关。