我怎么感受 ConcurrentDictionary<,> 不是线程安全的喃?

直接上代码安全

    class Program
    {
        static readonly ConcurrentDictionary<string, Person> Dic = new ConcurrentDictionary<string, Person>();
        static void Main(string[] args)
        {
            for (int i = 0; i < 500; i++)
            {
                Task.Run(() => { GetPerson("wjire"); });
            }
            Console.ReadKey();
        }
        private static Person GetPerson(string key)
        {
            return Dic.GetOrAdd(key, k => new Person());
        }
    }

    class Person
    {
        public Person()
        {
            Console.WriteLine("new Person()");
        }
    }

 

输出:spa

 

WHAT FUCK!线程

哪位大佬能出来解释下么?有点懵逼啊!code

难道有些方法是线程安全的,有些方法不是?对象

 

想了下,好像也不能说不是线程安全,我感受虽然建立了4个对象,可是后面3次建立时,key 还不存在,当委托执行完毕,也就是对象建立完成,准备添加的时候,blog

发现 key 已经存在了,因而终止了添加操做,而是把已经存在的值取出来返给调用者.string

 

感受应该是这样.it

相关文章
相关标签/搜索