ConcurrentDictionary的ContainsKey 保证了多线程读取、写入没问题,线程安全。但是并不能保证Key 重复 。这里多线程的时候,Key可能重复导致Add失败,请优先使用 AddOrUpdate 。
using System; using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; using System.Reflection; namespace MulThreadTest { //下面的示范是一个并发插入错误的写法。 ///方案1:加锁--lock (ReaderWriterLockSlim);方案2:使用TryAddOrUpdate class MainClass { public static void Main (string[] args) { var dic = new ConcurrentDictionary<int,int> (); for (int i = 0; i < 10; i++) { var th = new Thread (new ParameterizedThreadStart ((state) => { var num = DoHelper.Instance.SayHello (); if (dic.ContainsKey (num)) { dic.AddOrUpdate (num, num, (m, n) => { return n; }); Console.WriteLine ("AddOrUpdate: " + num.ToString ()); } else { var addRes = dic.TryAdd (num, num); if (false == addRes) { Console.WriteLine ("Error add. num exits"); } } })); th.Start (i); } Console.ReadKey (); } } public class DoHelper { public static DoHelper Instance = new DoHelper (); public int SayHello () { var num = new Random (DateTime.Now.Millisecond).Next (); return num; } } }
参考:
https://referencesource.microsoft.com/#mscorlib/system/Collections/Concurrent/ConcurrentDictionary.cs,4d0f4ac22dbeaf08