• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

c#实现golang的channel

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

使用.NET的 BlockingCollection<T>来包装一个ConcurrentQueue<T>来实现golang的channel。

代码如下:

public class Channel<T>
{
    private BlockingCollection<T> _buffer;

    public Channel() : this(1) { }
    public Channel(int size)
    {
        _buffer = new BlockingCollection<T>(new ConcurrentQueue<T>(), size);
    }

    public bool Send(T t)
    {
        try
        {
            _buffer.Add(t);
        }
        catch (InvalidOperationException)
        {
            // will be thrown when the collection gets closed
            return false;
        }
        return true;
    }

    public bool Receive(out T val)
    {
        try
        {
            val = _buffer.Take();
        }
        catch (InvalidOperationException)
        {
            // will be thrown when the collection is empty and got closed
            val = default(T);
            return false;
        }
        return true;
    }

    public void Close()
    {
        _buffer.CompleteAdding();
    }

    public IEnumerable<T> Range()
    {
        T val;
        while (Receive(out val))
        {
            yield return val;
        }
    }
}

测试程序

[TestCase]
    public void TestSPSC_Performance()
    {
        int numItems = 10000000;
        int numIterations = 10;

        var stopWatch = new Stopwatch();
        stopWatch.Start();
        for (int i = 0; i < numIterations; ++i)
        {
            var channel = new Channel<int>(100);
            var writer = Task.Factory.StartNew(() => { foreach (var num in Enumerable.Range(1, numItems)) { channel.Send(num); } channel.Close(); });
            var reader = Task.Factory.StartNew<List<int>>(() => { var res = new List<int>(numItems); foreach (var num in channel.Range()) { res.Add(num); } return res; });
            Task.WaitAll(writer, reader);
        }
        stopWatch.Stop();

        var elapsedMs = stopWatch.Elapsed.TotalMilliseconds;
        Console.WriteLine("SPSC N = {0}: {1:.00}ms/iteration, {2:.00}ns/item (tx+rx)", numItems,  elapsedMs / numIterations, elapsedMs * 1000.0 / numItems / numIterations);
    }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#winform获取当前路径发布时间:2022-07-10
下一篇:
C#变量初始化发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap