1. 程式人生 > >C#字典Dictionay多線程讀是否是安全的

C#字典Dictionay多線程讀是否是安全的

color console 多線程 ram new sleep str 混亂 線程

答案:是線程安全的,只讀不寫多線程下,完全不需要加鎖!

測試代碼:

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萬個線程讀字典,看看是否混亂:

    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(); }

完全不需要擔心,放心

C#字典Dictionay多線程讀是否是安全的