Use golang-like channel programming in C #(1 ),
BusterWood. Channels is an open source library for Channels implemented on C. By using this class library, we can implement channel programming methods similar to golang and goroutine in C. Here we will introduce three simple channel examples. Send messages through a channel (https://gobyexample.com/channels ):
static void SimpleMessage(){ var channel = new Channel<String>(); Task.Run(async () => { await channel.SendAsync("Hello World!"); }); var message = channel.Receive(); Console.WriteLine(message);}
In the above example, we send messages through a channel in the TPL Task. The main thread receives messages through Receive. Here, because our SimpleMessage method is not an async method, we cannot use ReceiveAsync to receive messages.
Channel message synchronization (https://gobyexample.com/channel-synchronization ):
static void ChannelSychronization() { var channel = new Channel<bool>(); Task.Run(async () => { Console.Write("Working..."); await Task.Delay(1000); Console.WriteLine("done"); await channel.SendAsync(true); }); channel.ReceiveAsync().Wait();}
In this example, the main thread is blocked by ReceiveAsync. After the TPL Task sends a message, the program ends.
Select multiple channels (https://gobyexample.com/select): When we need to receive information from multiple channels, we can use Select to achieve:
static void Select() { var channel1 = new Channel<String>(); var channel2 = new Channel<String>(); Task.Run(async () => { await Task.Delay(1000); await channel1.SendAsync("one"); }); Task.Run(async () => { await Task.Delay(2000); await channel1.SendAsync("two"); }); for (var i = 0; i < 2; i++) { new Select() .OnReceive(channel1, msg1 => { Console.WriteLine("received " + msg1); }) .OnReceive(channel2, msg2 => { Console.WriteLine("received " + msg2); }).ExecuteAsync().Wait(); }}
In the preceding example, we use Select to receive information from both Channel 1 and Channel 2.
This C # Open-source library can be found in composer. net 4.6 and. net core. The code in the above example can be found at https://github.com/mcai4gl2/channelexamples. the example code can be run on .net core. Here we only introduce the basic applications of several channels. We will introduce more examples of channels in the future.