zoukankan      html  css  js  c++  java
  • wrap ConcurrentDictionary in BlockingCollection

    ConcurrentDictionary<int, BlockingCollection<string>> mailBoxes = new ConcurrentDictionary<int, BlockingCollection<string>>();
            int maxBoxes = 5;
    
            CancellationTokenSource cancelationTokenSource = new CancellationTokenSource();
            CancellationToken cancelationToken = cancelationTokenSource.Token;
    
            Random rnd = new Random();
            // Producer
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    int index = rnd.Next(0, maxBoxes);
                    // put the letter in the mailbox 'index'
                    var box = mailBoxes.GetOrAdd(index, new BlockingCollection<string>());
                    box.Add("some message " + index, cancelationToken);
                    Console.WriteLine("Produced a letter to put in box " + index);
    
                    // Wait simulating a heavy production item.
                    Thread.Sleep(1000);
                }
            });
    
            // Consumer 1
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    int index = rnd.Next(0, maxBoxes);
                    // get the letter in the mailbox 'index'
                    var box = mailBoxes.GetOrAdd(index, new BlockingCollection<string>());
                    var message = box.Take(cancelationToken);
                    Console.WriteLine("Consumed 1: " + message);
    
                    // consume a item cost less than produce it:
                    Thread.Sleep(50);
                }
            });
    
            // Consumer 2
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    int index = rnd.Next(0, maxBoxes);
                    // get the letter in the mailbox 'index'
                    var box = mailBoxes.GetOrAdd(index, new BlockingCollection<string>());
                    var message = box.Take(cancelationToken);
                    Console.WriteLine("Consumed 2: " + message);
    
                    // consume a item cost less than produce it:
                    Thread.Sleep(50);
                }
            });
    
            Console.ReadLine();
            cancelationTokenSource.Cancel();
  • 相关阅读:
    打印杨辉三角
    插值排序
    各种冒泡排序法
    Linux系统命令符01
    2.1博客系统 |基于form组件和Ajax实现注册登录
    python面试笔试题,你都会了吗?快来复习
    1.2博客系统 |登录页| 验证码
    1.1博客系统| 表结构
    第五章:5.2面向对象-绑定方法和非绑定方法| 内置方法 |元类
    11.Django|中间件
  • 原文地址:https://www.cnblogs.com/zeroone/p/8043377.html
Copyright © 2011-2022 走看看