答案:是線程安全的,只讀不寫多線程下,徹底不須要加鎖!安全
測試代碼:多線程
using System; using System.Diagnostics; using System.Threading; using System.Collections.Generic; namespace hello { public class ThreadSafe { Dictionary<int, int> dits = new Dictionary<int, int>(); public ThreadSafe() { for (int i = 0; i < 100; i++) { dits.Add(i, i); } } public void Test(object i) { int t = Convert.ToInt32(i); int v; Thread.Sleep(1); dits.TryGetValue(t, out v); if (!t.Equals(v)) { Console.WriteLine("i:{0},v:{1}", t, v); } } } }
模擬5萬個線程讀字典,看看是否混亂:dom
static void Main(string[] args) { ThreadSafe ts = new ThreadSafe(); Random random=new Random(); Console.WriteLine("Hello World!2"); for (int i = 0; i < 50000; i++) { new Thread(new ParameterizedThreadStart(ts.Test)).Start(random.Next(100)); } Console.Read(); }
徹底不須要擔憂,放心測試