C# CncurrentDictionary

ConcurrentDictionary GetOrAdd方法不是线程安全的
两个add方法委托都执行了。
最后有可能是Hello from t1 或者Hello from t2。

            Thread t1 = new Thread(() =>
            {
                store.GetOrAdd(0, i =>
                {
                    string msg = "Hello from t1";
                    Trace.WriteLine(msg);
                    Thread.SpinWait(10000);
                    return msg;
                });
            });

            Thread t2 = new Thread(() =>
            {
                store.GetOrAdd(0, i =>
                {
                    string msg = "Hello from t2";
                    Trace.WriteLine(msg);
                    Thread.SpinWait(10000);
                    return msg;
                });
            });

            t1.Start();
            t2.Start();
            t1.Join();
            t2.Join();
            foreach (var item in store.Values)
            {
                Console.WriteLine(item);
            }
            Console.Read();

ConcurrentDictionary Pitfall - Are delegates factories from GetOrAdd and AddOrUpdate synchronized?
Extension methods to make ConcurrentDictionary GetOrAdd and AddOrUpdate thread safe when using valueFactory delegates

你可能感兴趣的:(C# CncurrentDictionary)