C# BlockingCollection(生产者/消费者)练习

最近接手同事C#代码,(话说我一个C++程序员干嘛做这种事情,可能我是韭菜吧),为了能够承接,特地去拜读了《C#图解教程》,入门还是不错的。

写代码嘛,异步编程肯定少不了,下面就是利用C# BlockingCollection功能模块编写的 生产者/消费者 demo(韭菜要自觉生产,提供给多人消费)。

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

namespace ConsoleApp2
{

    class Collection
    {
        public static BlockingCollection<int> bc = new BlockingCollection<int>();
    }
    class Producer
    {
        public static async Task Producer_fun()
        {
            await Task.Run(() => {
                for (int i = 0; i < 100; i++)
                {
                    Thread.Sleep(50);
                    Collection.bc.Add(i);
                    Console.WriteLine($"韭菜生产 {i}");
                }
                Collection.bc.CompleteAdding();
            });
        }
    }

    class Consumer
    {
        public static int n = 0;
        public static async Task Consumer_fun(string str)
        {
            await Task.Run(() =>
            {
                while(true){
                    Thread.Sleep(200);
                    if (Collection.bc.TryTake(out n))
                    {
                        Console.WriteLine($"{str}掠夺 {n}");
                    }
                    else
                    {
                        if (Collection.bc.IsCompleted)
                            break;
                    }
                }

            });
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Task t1 = Producer.Producer_fun();
            Task t2 = Consumer.Consumer_fun("JD");
            Task t3 = Consumer.Consumer_fun("ali");
            Task t4 = Consumer.Consumer_fun("QQ");
            Task t5 = Consumer.Consumer_fun("apple");
            Task.WaitAll(t1, t2, t3,t4,t5);

        }
    }
}

 

相对于C++来说,C#的BlockingCollection(生产/消费)使用真的非常方便,还线程安全。。。。

posted @ 2022-10-25 16:51  补码  阅读(220)  评论(0编辑  收藏  举报