// See https://aka.ms/new-console-template for more information
using System;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
public class Program
{
public static async Task Main(string[] args)
{
// 建立一個單向的、無界的 Channel,用於傳送字串
var channel = Channel.CreateUnbounded<string>();
// 啟動一個新的任務來執行接收操作
var receivingTask = Task.Run(async () =>
{
// 無限迴圈,直到接收到特定的訊息
while (await channel.Reader.WaitToReadAsync())
{
while (channel.Reader.TryRead(out var message))
{
// 如果接收到特定的訊息,則結束迴圈
if (message == "END")
{
Console.WriteLine("Received END. Exiting...");
return;
}
Console.WriteLine($"Received: {message}");
}
}
});
// 向 Channel 寫入資料,模擬傳送操作
await channel.Writer.WriteAsync("Hello");
await channel.Writer.WriteAsync("World");
// 透過寫入特定的訊息來通知接收方結束操作
//await channel.Writer.WriteAsync("END");
Task.Factory.StartNew(async () =>
{
while(true)
{
await channel.Writer.WriteAsync(Console.ReadLine());
}
});
// 等待接收任務完成
await receivingTask;
}
}