c# System.Threading.Channels.Channel<T>的使用

2020-11-27 01:55

阅读:598

标签:message   reader   writer   个数   public   rgs   try   oid   ons   

先贴一个代码

class Program
    {
        static void Main(string[] args)
        {
            var channels = Channel.CreateBounded(2);
            var mail1 = new Mail(1, $"Message #{1}");
            var mail2 = new Mail(2, $"Message #{1}");
            var mail3 = new Mail(3, $"Message #{1}");
            var mail4 = new Mail(4, $"Message #{1}");
            var mail5 = new Mail(5, $"Message #{1}");
            var mail6 = new Mail(6, $"Message #{1}");

            var b0 = channels.Writer.TryWrite(mail1);
            b0 = channels.Writer.TryWrite(mail2);
            b0 = channels.Writer.TryWrite(mail3);
            b0 = channels.Writer.TryWrite(mail4);
            b0 = channels.Writer.TryWrite(mail5);
            b0 = channels.Writer.TryWrite(mail6);
            Mail mail;
            var b1 = channels.Reader.TryRead(out mail);
            b1 = channels.Reader.TryRead(out mail);
            b1 = channels.Reader.TryRead(out mail);
            b1 = channels.Reader.TryRead(out mail);
            b1 = channels.Reader.TryRead(out mail);
            b1 = channels.Reader.TryRead(out mail);

            Console.WriteLine("Hello World!");
        }

        
    }
    public class Mail
    {
        public Mail(int id, string content)
        {
            Id = id;
            Content = content;
        }

        public int Id { get; }
        public string Content { get; }
    }

Channel 通道的意思

Writer写入对象后会保存起来,等到reader 读取后就消费掉, 写入读取按照队列的形式,即 先写的先读取
CreateBounded 可以做一些设置,设置大小个数 ,如上述 Channel.CreateBounded(2);
CreateUnbounded 无限制 Channel.CreateUnbounded();
待续

c# System.Threading.Channels.Channel的使用

标签:message   reader   writer   个数   public   rgs   try   oid   ons   

原文地址:https://www.cnblogs.com/microestc/p/11929891.html


评论


亲,登录后才可以留言!