设为首页 加入收藏

TOP

C#字典Dictionay多线程读是否是安全的
2019-09-17 17:38:52 】 浏览:19
Tags:字典 Dictionay 线程 是否是 安全

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

测试代码:

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#断点调试时属性get块逻辑执行多.. 下一篇Redis in .NET Core 入门:(5) So..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目