当前位置: 移动技术网 > IT编程>开发语言>.net > C#字典Dictionay多线程读是否是安全的

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

2019年01月26日  | 移动技术网IT编程  | 我要评论

青岛市黄岛区邮编,东汉书院校歌,nuk和贝亲哪个好

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

测试代码:

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

完全不需要担心,放心

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网