我怎麼感受 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

相關文章
相關標籤/搜索