我怎么感觉 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()");
        }
    }

输出:

WHAT FUCK!

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

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

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

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

感觉应该是这样.

猜你喜欢

转载自www.cnblogs.com/refuge/p/12207927.html