System.IO.MemoryStream ms = new System.IO.MemoryStream(); // write to it ms.Write(new byte[] { 1,2,3,4,5,6,7 },7); // go to the begining ms.Seek(0,System.IO.SeekOrigin.Begin); // Now read from it byte[] myBuffer = new byte[7]; ms.Read(myBuffer,7);
现在我想知道是否可以从一个线程写入内存流,并从单独的线程读取该流.
解决方法 由于Stream处于状态已满,您不能同时使用2个线程寻求功能的流.例如NetworkStream有2个通道,一个用于阅读,一个用于写入,因此不能支持寻找.如果您需要寻找功能,则需要创建2个流,一个用于读取,另一个用于写入.否则,您可以简单地创建一个新的Stream类型,它允许通过独占访问底层流并恢复其写入/读取位置从底层内存流读取和写入.一个原始的例子是:
class ProducerConsumerStream : Stream{ private Readonly MemoryStream innerStream; private long readposition; private long writeposition; public ProducerConsumerStream() { innerStream = new MemoryStream(); } public overrIDe bool CanRead { get { return true; } } public overrIDe bool CanSeek { get { return false; } } public overrIDe bool CanWrite { get { return true; } } public overrIDe voID Flush() { lock (innerStream) { innerStream.Flush(); } } public overrIDe long Length { get { lock (innerStream) { return innerStream.Length; } } } public overrIDe long position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public overrIDe int Read(byte[] buffer,int offset,int count) { lock (innerStream) { innerStream.position = readposition; int red = innerStream.Read(buffer,offset,count); readposition = innerStream.position; return red; } } public overrIDe long Seek(long offset,SeekOrigin origin) { throw new NotSupportedException(); } public overrIDe voID SetLength(long value) { throw new NotImplementedException(); } public overrIDe voID Write(byte[] buffer,int count) { lock (innerStream) { innerStream.position = writeposition; innerStream.Write(buffer,count); writeposition = innerStream.position; } }}总结
以上是内存溢出为你收集整理的c# – MemoryStream有一个线程写入它和另一个读取全部内容,希望文章能够帮你解决c# – MemoryStream有一个线程写入它和另一个读取所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)