代码改变世界

C#字典Dictionay多线程读是否是安全的

2019-01-25 22:57  slmk  阅读(2731)  评论(1编辑  收藏  举报

答案:是线程安全的,只读不写多线程下,完全不需要加锁!

测试代码:

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

完全不需要担心,放心