c# System.Threading.Channels.Channel<T>的使用
先贴一个代码
class Program
{
static void Main(string[] args)
{
var channels = Channel.CreateBounded<Mail>(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<Mail>(2);
CreateUnbounded 无限制 Channel.CreateUnbounded<Mail>();
待续
using System; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; namespace Cmd { class Program { static void Main(string[] args) { var Instance = Channel.CreateUnbounded<int>(); Task.Run(() => { for (int i = 1; i < 101; i++) { Instance.Writer.TryWrite(i); Thread.Sleep(1_000); } }); Parallel.For(1, 100, async (idx, state) => { var num = await Instance.Reader.ReadAsync(); Console.WriteLine(num); }); Thread.Sleep(1000_000); } } }