ConcurrentDictionary

例子1

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var dic = new ConcurrentDictionary<int, int>();

            for (int i = 0; i < 6; i++)
            {
                Console.WriteLine(i + "  count");
                runInNewThread(i);
            }

            void runInNewThread(int i)
            {
                var thread = new Thread(para => dic.GetOrAdd(1, _ => getNum((int)para)));
                thread.Start(i);
            }

            int getNum(int i)
            {
                Console.WriteLine($"Factory invoke. got {i}");
                return i;
            }

            Console.ReadKey();
        }
}
  • 运行结果可能为以下之一


    例1-1

    例1-2

    例1-3

    例1-4

    例1-5

例子2

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ConcurrentDictionary<int, int> cd = new ConcurrentDictionary<int, int>();

            // Bombard the ConcurrentDictionary with 10000 competing AddOrUpdates
            Parallel.For(0, 10000, i =>
            {
                // Initial call will set cd[1] = 1.  
                // Ensuing calls will set cd[1] = cd[1] + 1
                cd.AddOrUpdate(1, 1, (key, oldValue) => oldValue + 1);
            });

            Console.WriteLine("After 10000 AddOrUpdates, cd[1] = {0}, should be 10000", cd[1]);

            // Should return 100, as key 2 is not yet in the dictionary
            int value = cd.GetOrAdd(2, (key) => 100);
            Console.WriteLine("After initial GetOrAdd, cd[2] = {0} (should be 100)", value);

            // Should return 100, as key 2 is already set to that value
            value = cd.GetOrAdd(2, 10000);
            Console.WriteLine("After second GetOrAdd, cd[2] = {0} (should be 100)", value);

            Console.ReadKey();
        }
}
  • 运行结果如下


    例2

例子3

using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var task1 = Task.Run(() => PrintValue("JeffckWang"));
            var task2 = Task.Run(() => PrintValue("cnblogs"));
            Task.WaitAll(task1, task2);

            PrintValue("JeffckyWang from cnblogs");
            Console.WriteLine($"Run count: {_runCount}");

            Console.ReadKey();
        }


        private static readonly ConcurrentDictionary<string, string> _dictionary
            = new ConcurrentDictionary<string, string>();
        private static int _runCount = 0;

        public static void PrintValue(string valueToPrint)
        {
            var valueFound = _dictionary.GetOrAdd("key",
                        x =>
                        {
                            Interlocked.Increment(ref _runCount);
                            Thread.Sleep(100);
                            return valueToPrint;
                        });
            Console.WriteLine(valueFound);
        }
    }
}

  • 运行结果可能为以下之一


    例3-1

    例3-2

例子4

using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            var task1 = Task.Run(() => PrintValue("JeffckWang"));
            var task2 = Task.Run(() => PrintValue("cnblogs"));
            Task.WaitAll(task1, task2);

            PrintValue("JeffckyWang from cnblogs");
            Console.WriteLine($"Run count: {_runCount}");

            Console.ReadKey();
        }

        private static int _runCount = 0;

        private static readonly ConcurrentDictionary<string, Lazy<string>> _lazyDictionary
          = new ConcurrentDictionary<string, Lazy<string>>();

        public static void PrintValue(string valueToPrint)
        {
            var valueFound = _lazyDictionary.GetOrAdd("key",
              x => new Lazy<string>(
                  () =>
                  {
                      Interlocked.Increment(ref _runCount);
                      Thread.Sleep(100);
                      return valueToPrint;
                  }));
            Console.WriteLine(valueFound.Value);
        }
    }
}

  • 运行结果可能为以下之一


    例4-1

    例4-2

具体过程分析请看参考

参考
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文主要讲了java中多线程的使用方法、线程同步、线程数据传递、线程状态及相应的一些线程函数用法、概述等。 首先讲...
    李欣阳阅读 2,527评论 1 15
  • 世间 是否有一种十万分不舍的真挚情感,而你却必须放弃? 是否也有人因为太过喜欢某个人或者爱某个人但必须放手狠心说再...
    井溢阅读 304评论 0 3
  • 麦田里的土壤不能根植树林。 草原的风马,也不如往前向往。 遗憾,像囚禁的飞鸟。 我如鱼刺卡于咽喉, 如信仰死于昨天...
    十二月_无言阅读 122评论 3 4
  • 明天一大早就要出发了,心情好复杂!今天安顿收拾了一天,纠结症又犯了,到底哪些东西可以不带?带的太多提不动,但一些物...
    土左旗357李新燕阅读 143评论 0 0
  • 今天是平安夜 想写的东西太多 大概有一箩筐。考完研周围的同学都得到解放 考好考差 回家过年。 希望大家安安静静 我...
    徐走你阅读 160评论 0 0