C# 生產者消費者實現

using System;
using System.Collections.Concurrent;
using System.ComponentModel.DataAnnotations;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;

namespace ConsoleApp25
{
    class Program
    {
        private static readonly CancellationTokenSource _cts = new CancellationTokenSource();
        static void Main(string[] args)
        {
            var blockingCollection = new BlockingCollection<Person>();
            var publishedChannel = Channel.CreateUnbounded<Person>(new UnboundedChannelOptions() { SingleReader = true, SingleWriter = true });

            var person = new Person("A");
            for (int i = 0; i < 10; i++)
            {
                blockingCollection.TryAdd(person);
                publishedChannel.Writer.TryWrite(person);
            }
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    var _person = blockingCollection.Take();//沒有數據時,會阻塞當前線程
                    Console.WriteLine($"from Channel:{_person.Name}");//輸出10次
                }
            });

            Task.Factory.StartNew(async () =>
                {
                    while (await publishedChannel.Reader.WaitToReadAsync(_cts.Token))//沒有數據時,會阻塞當前線程
                    {
                        while (publishedChannel.Reader.TryRead(out var _person))
                        {
                            Console.WriteLine($"from BlockingCollection:{_person.Name}");//輸出10次
                        }
                    }
                });

            Console.ReadKey();
        }
    }

    public class Person
    {
        public Person(string name)
        {
            Name = name;
        }

        public string Name { get; private set; }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章