C# BlockingCollection实现线程间通信

C# BlockingCollection实现线程间通信

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Security.Authentication.ExtendedProtection;
using System.Text;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            sender.Start(1);
            receive1.Start(2);
            receive2.Start(3);
            sender.Join();
            Thread.Sleep(3000);
            receive1.Interrupt();
            receive2.Interrupt();

            receive1.Join();
            receive2.Join();    


            Console.ReadKey();
        }
        #region BlockingCollection实现线程间通信
        static BlockingCollection<Message> blockCollenction = new BlockingCollection<Message>(new ConcurrentQueue<Message>());
        static Thread sender = new Thread(SendMsg);

        static Thread receive1 = new Thread(ReceiveMsg);
        static Thread receive2 = new Thread(ReceiveMsg);

        static void SendMsg(object id)
        {
            for (int i = 0; i < 20; i++)
            {
                blockCollenction.Add(new Message((int)id, i.ToString()));
                Console.WriteLine($"【线程{id}】发送了【{i}】");
            }
        }

        static void ReceiveMsg(object id)
        {
            try
            {
                while (true)
                {
                    Message message =  blockCollenction.Take();
                    Console.WriteLine($"【线程{id}】从【线程{message.id}】接收了【{message.content}】");
                    Thread.Sleep(1);
                }
            }
            catch (ThreadInterruptedException ex)
            {
                Console.WriteLine($"接收结束");
            }
        }

    }
}

class Message
{
    public int id;
    public string content;

    public Message(int _id, string _content)
    {
        id = _id;
        content = _content;
    }
}

#endregion


你可能感兴趣的:(c#)