c# - MemoryStream 有一个线程写入它,另一个线程读取它

标签 c# multithreading stream memorystream

这就是我写入流然后使用 1 个线程从中读取的方式:

        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);

现在我想知道是否可以从一个线程写入内存流并从另一个线程读取该流。

最佳答案

您不能使用具有同时从 2 个线程寻找功能的 Stream,因为 Stream 是满状态的。例如NetworkStream 有 2 个 channel ,一个用于读取,一个用于写入,因此不支持搜索。

如果需要seeking capabilities,需要创建2个streams,一个读一个写。否则,您可以简单地创建一个新的 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;
        }
    }
}

关于c# - MemoryStream 有一个线程写入它,另一个线程读取它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12328245/

相关文章:

c# - 使用 LINQ 在对象列表中分组来执行聚合

c# - 检查加载程序集的窗口是否打开

python - 在Python中使用多线程进行实时视频处理

JAVA 8 可选 map 否则

stream - 检查点上的 Flume NullPointerExceptions

c# - 在 ASP.NET MVC 中,没有 AntiForgeryToken 的删除操作方法不安全吗?

c# - 使用 UnityAction 传递参数

c# - SQL 冲突,来自不同线程/进程的并发 UPDATE 和 SELECT

java - 如何取消android studio中的特定线程?

带有发布数据的 php file_get_contents