美文网首页
C# CncurrentDictionary

C# CncurrentDictionary

作者: johnwonder | 来源:发表于2016-08-31 14:02 被阅读0次

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

    ConcurrentDictionary GetOrAdd方法不是线程安全的两个add方法委托都执行了。最后有可能...

  • C# 6/7 新功能

    C#新功能 一、C#历史演变 C# 1,Visual Studio .NET 2002: C# 初版。 C# 1....

  • Unity中的C#编程-零基础(Unity2017)

    01 什么是C#编程语言 人与机器之间的语言,C#脚本,C#源代码,C#源文件 Unity支持的俩种语言:C# S...

  • 目录 - C#

    总目录 C# 第01局:泛型 C# 第02局:反射 C# 第03局:特性 C# 第04局:委托 C# 第05局:事...

  • 使用GRPC

    C# .NET Framework 对于C# .NET Framework平台,使用GRPC for C#,GRP...

  • C#-分享几种常用的编码转换,base64、MD5、string

    C# Base64编码 C# 文件与二进制流 C# MD5加密 C# string和byte[]

  • 设计模式

    《C#设计模式》 《C#设计模式》-设计模式概述 《C#设计模式》-面向对象设计原则 《C#设计模式》-单例模式 ...

  • 对Lua ,C,C#互相调用的理解

    几种情况讨论 C调用Lua C调用C# C#调用C C#调用Lua Lua调用C Lua调用C# Lua调用C 本...

  • C#基础

    微软Doc: C# 8.0 新增功能 —Using 声明 C# 8.0 新增功能 —Readonly C# 8.0...

  • 游戏系统机器人

    mono C#项目简介 想必C#玩家往往受到Java玩家的嘲笑,不能写移动端。mono C#的目的正是通过C#的中...

网友评论

      本文标题:C# CncurrentDictionary

      本文链接:https://www.haomeiwen.com/subject/akmxettx.html