是否有一个在内存流,阻止像一个文件流 [英] Is there an in memory stream that blocks like a file stream

查看:131
本文介绍了是否有一个在内存流,阻止像一个文件流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的要求我提供一个实现此接口的对象库:

I'm using a library that requires I provide an object that implements this interface:

public interface IConsole {
    TextWriter StandardInput { get; }
    TextReader StandardOutput { get; }
    TextReader StandardError { get; }
}



对象的读者后来就习惯了库:

The object's readers then get used by the library with:

IConsole console = new MyConsole();
int readBytes = console.StandardOutput.Read(buffer, 0, buffer.Length);



通常实施IConsole类有StandardOutput流从外部进程的到来。在这种情况下,console.StandardOutput.Read通过阻断,直到有写入StandardOutput流的一些数据呼叫的工作。

Normally the class implementing IConsole has the StandardOutput stream as coming from an external process. In that case the console.StandardOutput.Read calls work by blocking until there is some data written to the StandardOutput stream.

我想要做的就是创建一个测试使用上StandardInput无论出现放回StandardInput MemoryStreams和回声的IConsole实现。我想:

What I'm trying to do is create a test IConsole implementation that uses MemoryStreams and echo's whatever appears on the StandardInput back onto the StandardInput. I tried:

MemoryStream echoOutStream = new MemoryStream();
StandardOutput = new StreamReader(echoOutStream);



但是,随着该问题的console.StandardOutput.Read将返回0,而不是块,直到有一些数据。反正我能得到一个MemoryStream阻止如果没有可用数据在内存流有不同的,我可以用?

But the problem with that is the console.StandardOutput.Read will return 0 rather than block until there is some data. Is there anyway I can get a MemoryStream to block if there is no data available or is there a different in memory stream I could use?

推荐答案

在最后,我发现了一个简单的方法从MemoryStream的继承和接管读取和写入的方法来做到这一点。

In the end I found an easy way to do it by inheriting from MemoryStream and taking over the Read and Write methods.

public class EchoStream : MemoryStream {

    private ManualResetEvent m_dataReady = new ManualResetEvent(false);
    private byte[] m_buffer;
    private int m_offset;
    private int m_count;

    public override void Write(byte[] buffer, int offset, int count) {
        m_buffer = buffer;
        m_offset = offset;
        m_count = count;
        m_dataReady.Set();
    }

    public override int Read(byte[] buffer, int offset, int count) {
        if (m_buffer == null) {
            // Block until the stream has some more data.
            m_dataReady.Reset();
            m_dataReady.WaitOne();    
        }

        Buffer.BlockCopy(m_buffer, m_offset, buffer, offset, (count < m_count) ? count : m_count);
        m_buffer = null;
        return (count < m_count) ? count : m_count;
    }
}

这篇关于是否有一个在内存流,阻止像一个文件流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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