在C#中使用類golang信道編程(一)


BusterWood.Channels是一個在C#上實現的信道的開源庫。通過使用這個類庫,我們可以在C#語言中實現類似golang和goroutine的信道編程方式。在這里我們介紹3個簡單的信道的例子。 
 
通過信道發送消息( 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);
}

在上面這個例子中,我們在TPL Task中通過信道發送消息。主線程通過Receive接收消息。這里,由於我們的SimpleMessage方法不是一個async方法,我們不能使用ReceiveAsync來接收消息。

 
信道消息同步( 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();
}

在這個例子中,主線程被ReceiveAsync堵塞,當TPL Task發送消息后,程序才結束。

 

選擇多個信道( https://gobyexample.com/select): 
當我們需要從多個信道中接收信息時,我們可以用Select來實現:
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();
    }
}

在上面的例子中,我們通過Select同時從兩個信道channel1和channel2接收信息。

 
這個C#的開源庫可以在 https://github.com/busterwood/Channels找到代碼,nuget文件名為BusterWood.Channels,最新版支持 .net 4.6和 .net core。上面例子的代碼可以在 https://github.com/mcai4gl2/ChannelExamples找到,例子代碼可以在.net core上運行。 這里我們只介紹了幾個信道的基本應用,以后我們還會進一步介紹更多的信道的例子。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM