我正在尝试使用Stream.Synchronized在两个C#操作之间发送字节来包装MemoryStream。每次消费者执行ReadByte时,它总是得到-1,表示流已关闭。当我逐步使用调试器时,生产者正在调用WriteByte。我从未获得有关消费者行为的任何数据。
static void Main(string[] args)
{
var memStream = new MemoryStream(100);
Stream dataStream = Stream.Synchronized(memStream);
Action producer = () =>
{
for (int i = 0; i < 256; i++)
{
dataStream.WriteByte(Convert.ToByte(i));
dataStream.Flush();
}
};
int total = 0;
Action consumer = () =>
{
int b;
do
{
b = dataStream.ReadByte();
if (b>=0)
total += b;
}
while (b < 255);
};
Parallel.Invoke(producer, consumer);
Console.Out.WriteLine("Total = {0}", total);
}
答案 0 :(得分:0)
similar question on SO可能会提供某些人的答案。
实现类似内容的其他选项包括PipeStream available at CodeProject,TransferStream from parallel-extensions-extras,或者在某些情况下只需标准System.Collections.Concurrent.BlockingCollection即可。
答案 1 :(得分:-1)
在消费者中,我需要寻找流的开头:
Action consumer = () =>
{
int b;
dataStream.Seek(0, SeekOrigin.Begin);
do
{
b = dataStream.ReadByte();
if (b >= 0)
total += b;
}
while (b < 255);
};