19

This is how I write to a stream then read from it using 1 thread:

        System.IO.MemoryStream ms = new System.IO.MemoryStream();

        // write to it
        ms.Write(new byte[] { 1, 2, 3, 4, 5, 6, 7 }, 0, 7);

        // go to the begining
        ms.Seek(0, System.IO.SeekOrigin.Begin);

        // now read from it
        byte[] myBuffer = new byte[7];
        ms.Read(myBuffer, 0, 7);

Now I was wondering if it is possible to write to the memory-stream from one thread and read that stream from a separate thread.

4

1 に答える 1

19

Stream はフル状態であるため、同時に 2 つのスレッドからシーク機能を使用して Stream を使用することはできません。たとえば、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 offset, int count)
    {
        lock (innerStream)
        {
            innerStream.Position = writePosition;
            innerStream.Write(buffer, offset, count);
            writePosition = innerStream.Position;
        }
    }
}
于 2012-09-08T05:34:34.753 に答える