使用Stream.Synchronized的生产者/消费者示例-消费者未获取任何数据 [英] Producer/Consumer example using Stream.Synchronized - Consumer isn't getting any data

查看:88
本文介绍了使用Stream.Synchronized的生产者/消费者示例-消费者未获取任何数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Stream.Synchronized 来包装MemoryStream。使用者每次执行ReadByte时,总是获得-1,表示流已关闭。当我通过调试器时,生产者正在调用WriteByte。我从没获得任何有关消费者行为的数据。

I'm trying to send bytes between two C# Actions using Stream.Synchronized to wrap a MemoryStream. Every time the consumer does a ReadByte, it always gets a -1, indicating the stream is closed. When I step thru with the debugger, the producer is calling WriteByte. I never get any data on the consumer action.

    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);
    }


推荐答案

有一个关于SO的类似问题,可能会提供一些答案。

There's a similar question on SO that might provide answers from some people.

其他实现此类操作的选项是可在CodeProject上使用的PipeStream 来自并行扩展名-extras的TransferStream ,或者在某些情况下只是标准的 System.Collections.Concurrent.BlockingCollection 可能有用。

Other options to implement something like this are the PipeStream available at CodeProject, the TransferStream from parallel-extensions-extras, or in some cases just a standard System.Collections.Concurrent.BlockingCollection might work.

这篇关于使用Stream.Synchronized的生产者/消费者示例-消费者未获取任何数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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