在生产者/消费者模式中,如果知道有一个消费者会保证读取流直到结束,或者在无法读取时进行处理,那么同步流就不需要维护自己的内部缓冲区,而是完全依赖于调用Read方法的调用者提供的缓冲区。在Read方法中,CoStream保存目标缓冲区的引用并等待它被填满。另一方面,Write方法将数据从源缓冲区复制到目标缓冲区,如果缓冲区准备好了,就向读取器发出信号,并等待另一个Read调用,如果源缓冲区中还有未消费的数据,或者返回到Write调用者。
使用CoStream时,不能在单线程中使用。至少需要两个线程,即读取和写入线程。两者都需要关闭(或处理)流,以便对方可以在结束时继续。
您将在附加的存档中找到的测试程序会在XmlDocument中加载一些XML文件,然后将其写入CoStream的实例:
C#
static CoStream costream = new TestCoStream();
static string outpath;
static void Main(string[] args)
{
// ...
XmlDocument doc = new XmlDocument();
doc.Load(args[0]);
outpath = args[1];
var reading_thread = new Thread(ReaderBody);
reading_thread.Start();
using (var pipe = XmlWriter.Create(costream, new XmlWriterSettings { CloseOutput = true }))
doc.Save(pipe);
reading_thread.Join();
}
读取线程简单地将其复制到输出文件:
C#
static void ReaderBody()
{
using (var reader = XmlReader.Create(costream, new XmlReaderSettings { CloseInput = true }))
using (var writer = XmlWriter.Create(outpath))
writer.WriteNode(reader, false);
}
TestCoStream类覆盖了CoStream的Read、Write和Flush方法,以展示后台发生了什么。
Reading 4096 bytes.
>4096 bytes read.
>Reading 4096 bytes.
4096 bytes read.
>Reading 4096 bytes.
114 bytes read.
>Reading 4096 bytes.
0 bytes read.
2014-12-14 - Version 1.0