channel
中也是有一个ConcurrentQueue
来维护的
using System.Threading.Channels;
var channel = Channel.CreateUnbounded<Message>();
//在赋值的时候,两个Task就开始执行了,下面的await就是为了等待执行完成
var sender1 = SendMessageAsync(channel.Writer, 1);
var sender2 = SendMessageAsync(channel.Writer, 2);
var receiver = ReceiveMessageAsync(channel.Reader, 3);
await Task.WhenAll(sender1, sender2);
channel.Writer.Complete();
await receiver;
async Task SendMessageAsync(ChannelWriter<Message> writer, int id)
{
for (int i = 0; i <= 20; i++)
{
await writer.WriteAsync(new Message(id, i.ToString()));
Console.WriteLine($"Thread {id} sent {i}");
await Task.Delay(100);
}
}
async Task ReceiveMessageAsync(ChannelReader<Message> reader, int id)
{
// try
// {
// while (!reader.Completion.IsCanceled)
// {
// var message = await reader.ReadAsync();
// Console.WriteLine($"Thread {id} received {message.Content} from {message.FromId}");
// }
// }
// catch (ChannelClosedException)
// {
// Console.WriteLine($"Thread {id} channel closed");
// }
await foreach (var message in reader.ReadAllAsync())
{
Console.WriteLine($"Thread {id} received {message.Content} from {message.FromId}");
}
}
record Message(int FromId, string Content);