IEnumerable的到流 [英] IEnumerable to Stream

查看:115
本文介绍了IEnumerable的到流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做些事情大致相当于低于code例子。我要生成和服务的数据流,而不在任何一个时间不一定具有整个数据在存储器中设置

好像我需要流的一些实现,它接受一个的IEnumerable<串> (或的IEnumerable<字节> )在其构造。该内部流将只走了IEnumerable作为流正在读取或根据需要。但我不知道任何流实现这样的。

我在正确的轨道上吗?你知道有什么方法可以做这样的事情?

 公共FileStreamResult调用getResult()
    {
        IEnumerable的<串GT;数据= GetDataForStream();        流的数据流= ToStringStream(Encoding.UTF8,数据);        返回文件(数据流,text / plain的,结果);
    }    私人的IEnumerable<串GT; GetDataForStream()
    {
        StringBuilder的SB;
        的for(int i = 0; I< 10000;我++)
        {
            产量返回i.ToString();
            收益回报为\\ r \\ n;
        }
    }    专用流ToStringStream(编码编码,IEnumerable的<串GT;数据)
    {
        //我必须写我自己的实现流?
        抛出新NotImplementedException();
    }


解决方案

我创建了一个名为 ProducerConsumerStream 类,做到这一点。生产者将数据写到流和消费者的读取。有在中间有一个缓冲区,这样生产者可以写入进取的一点点。可以定义的缓冲区的大小。

无论如何,如果它不是的究竟的你要找的东西,我怀疑它会给你它是如何做一个好主意。请参见建设新型的流的。

I would like to do something roughly equivalent to the code example below. I want to generate and serve a stream of data without necessarily having the entire data set in memory at any one time.

It seems like I would need some implementation of Stream that accepts an IEnumerable<string> (or IEnumerable<byte>) in its constructor. Internally this Stream would only walk the IEnumerable as the Stream is being read or as needed. But I don't know of any Stream implementation like this.

Am I on the right track? Do you know of any way to do something like this?

    public FileStreamResult GetResult()
    {
        IEnumerable<string> data = GetDataForStream();

        Stream dataStream = ToStringStream(Encoding.UTF8, data);

        return File(dataStream, "text/plain", "Result");
    }

    private IEnumerable<string> GetDataForStream()
    {
        StringBuilder sb;
        for (int i = 0; i < 10000; i++)
        {
            yield return i.ToString();
            yield return "\r\n";
        }
    }

    private Stream ToStringStream(Encoding encoding, IEnumerable<string> data)
    {
        // I have to write my own implementation of stream?
        throw new NotImplementedException();
    }

解决方案

I created a class called ProducerConsumerStream that does this. The producer writes data to the stream and the consumer reads. There's a buffer in the middle so that the producer can "write ahead" a little bit. You can define the size of the buffer.

Anyway, if it's not exactly what you're looking for, I suspect it will give you a good idea of how it's done. See Building a new type of stream.

这篇关于IEnumerable的到流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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