c# – MemoryStream有一个线程写入它和另一个读取

前端之家收集整理的这篇文章主要介绍了c# – MemoryStream有一个线程写入它和另一个读取前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我如何写入一个流,然后使用1个线程读取它:
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;
        }
    }
}
原文链接:https://www.f2er.com/csharp/96664.html

猜你在找的C#相关文章