有没有不使用OS管的管状.NET Stream类? [英] Is there a pipe-like .NET Stream class that doesn't use OS pipes?

查看:72
本文介绍了有没有不使用OS管的管状.NET Stream类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C#/。NET(Xamarin /单声道,真的)。

Using C#/.NET (Xamarin/Mono, really).

我有一个类的方法(A),它接受一个流写入到, 而且我还有一个类的方法(B),它接受一个流的读取。

I have a class with a method (A) that accepts a stream that it writes to, and I have another class with a method (B) that accepts a stream to read from.

我想要传递给两个(A)中的流和(B),使得当 (一)写入流,这些数据可以通过(B)来读取。

I want to have a stream that is passed to both (A) and (B), such that when (A) writes to the stream, that data can be read by (B).

有没有已经不使用操作系统的管道这样的野兽?

Is there already such a beast that doesn't using OS pipes?

推荐答案

我会用的 BlockingCollection 。例如

BlockingCollection<int> bc = new BlockingCollection<int>();
Task.Run(() => new Reader(bc).DoWork());
Task.Run(() => new Writer(bc).DoWork());


public class Reader
{
    BlockingCollection<int> _Pipe = null;
    public Reader(BlockingCollection<int> pipe)
    {
        _Pipe = pipe;
    }

    public void DoWork()
    {
        foreach(var i in _Pipe.GetConsumingEnumerable())
        {
            Console.WriteLine(i);
        }
        Console.WriteLine("END");
    }
}

public class Writer
{
    BlockingCollection<int> _Pipe = null;
    public Writer(BlockingCollection<int> pipe)
    {
        _Pipe = pipe;
    }

    public void DoWork()
    {
        for (int i = 0; i < 50; i++)
        {
            _Pipe.Add(i);
            Thread.Sleep(100);
        }
        _Pipe.CompleteAdding();
    }
}

这篇关于有没有不使用OS管的管状.NET Stream类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆