Busterwood.channels is an open-source library of channels implemented on C #. By using this class library, we can implement channel programming like Golang and Goroutine in the C # language. Here we introduce 3 examples of simple channels. Send message via Channel (Https://gobyexample.com/channels):
Static void Simplemessage () { varnew channel<string>(); Task.run (async () = { await channel. SendAsync ("Hello world! " ); }); var message = channel. Receive (); Console.WriteLine (message);}
In the above example, we send a message through the channel in a 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 voidchannelsychronization () {varChannel =Newchannel<BOOL>(); Task.run (Async() ={Console.Write ("Working ..."); awaitTask.delay ( +); Console.WriteLine (" Done"); awaitChannel. SendAsync (true); }); Channel. Receiveasync (). Wait ();}
In this example, the main thread is blocked by Receiveasync, and the program ends when the TPL task sends the message.
Select multiple channels (https://gobyexample.com/select): When we need to receive information from multiple channels, we can use Select to implement:
Static voidSelect () {varChannel1 =NewChannel<string>(); varChannel2 =NewChannel<string>(); Task.run (Async() = { awaitTask.delay ( +); awaitChannel1. SendAsync (" One"); }); Task.run (Async() = { awaitTask.delay ( -); awaitChannel1. SendAsync (" Both"); }); for(vari =0; I <2; i++) { NewSelect (). OnReceive (Channel1, MSG1={Console.WriteLine ("received"+MSG1); }) . OnReceive (Channel2, MSG2={Console.WriteLine ("received"+MSG2); }). Executeasync (). Wait (); }}
In the example above, we receive information from both channels Channel1 and Channel2 through select.
This C # Open Source Library can find code in Https://github.com/busterwood/Channels, the NuGet file is named Busterwood.channels, and the latest version supports. NET 4.6 and. NET Core. The code for the example above can be found in https://github.com/mcai4gl2/ChannelExamples, and the example code can run on. NET Core. Here we only introduce a few basic applications of the channel, we will further introduce more examples of the channel.
Programming with class Golang channels in C # (i)