我使用的库需要我提供一个实现此接口的对象:
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.
我想要做的是创建一个测试 IConsole 实现,它使用 MemoryStreams 并将标准输入上出现的任何内容回显到标准输入上.我试过了:
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 并接管 Read 和 Write 方法.
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;
}
}
这篇关于是否有像文件流一样阻塞的内存流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!