问题
Using C#/.NET (Xamarin/Mono, really).
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.
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?
回答1:
i would use BlockingCollection. For example
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();
}
}
回答2:
You can create one around a MemoryStream, let's call it a ConcurrentMemoryStream.
You will need to make sure all the reads and writes are synchronized. You will also need to keep two pointers - one for reading and the other for writing, and seek to the proper place before a read or write operation.
Oh, and see this: https://stackoverflow.com/a/12328307/871910, as @mike z pointed out in a comment.
来源:https://stackoverflow.com/questions/21357933/is-there-a-pipe-like-net-stream-class-that-doesnt-use-os-pipes