美文网首页
ConcurrentDictionary

ConcurrentDictionary

作者: 泱千澈 | 来源:发表于2020-03-19 00:05 被阅读0次

例子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

具体过程分析请看参考

参考

相关文章

网友评论

      本文标题:ConcurrentDictionary

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