使用Stream.BeginRead的顺序异步读取 [英] Sequential asynchronous reads using Stream.BeginRead

查看:575
本文介绍了使用Stream.BeginRead的顺序异步读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个类,该类公开流的一个小节以供读取.由于可以同时从多个不同的小节中读取数据,因此任何一次都只能激活一个操作.

I'm writing a class that exposes a subsection of a stream for reading. Since data may be read from multiple different subsections at the same time, only one operation may be active at any one time.

我的想法是在每次操作之前锁定基础流.将流锁定在BeginRead调用周围是否足以确保从基础流中不同位置进行的并发异步读取正确发生?

I had the idea of locking the underlying stream before every operation. Is locking the stream around the BeginRead call sufficient to ensure that concurrent asynchronous reads from different positions in the underlying stream happen correctly?

public sealed class SubStream : Stream
{
    // ...

    public override IAsyncResult BeginRead(byte[] buffer, int offset, int count,
        AsyncCallback callback, object state)
    {
        lock (this.baseStream)
        {
            this.baseStream.Seek(this.offset + this.position, SeekOrigin.Begin);
            return this.baseStream.BeginRead(buffer, offset, count,
                callback, state);
        }
    }

    public override int EndRead(IAsyncResult asyncResult)
    {
        int read;
        lock (this.baseStream)
        {
            read = baseStream.EndRead(asyncResult);
            this.position += read;
        }
        return read;
    }

    // Read() and ReadByte() also lock on this.baseStream (not shown).

    // ...
}

例如,如果线程A调用BeginRead,则会获取基本流上的锁.现在,线程B调用BeginRead,并且必须等待锁被释放.线程A设置基本流的位置并启动异步读取操作.然后释放锁.然后,线程B获取锁定并更改基本流的位置,并开始另一个异步读取操作.然后,在某个时间之后,从线程A的异步读取完成.我可以确定这是从基本流的原始位置读取的吗?如果没有,我该如何解决?

For example, if thread A calls BeginRead, a lock on the base stream is acquired. Now thread B calls BeginRead and has to wait for the lock to be released. Thread A sets the position of the base stream and starts an asynchronous read operation. Then releases the lock. Thread B then acquires the lock and changes the position of the base stream and starts another asynchronous read operation. Then, sometime later, the asynchronous read from thread A completes. Can I be sure that this reads from the original position in the base stream? If not, how do I fix it?

推荐答案

在给定的代码片段中,您将从同一位置读取多次.将位置更新移至BeginRead功能.除此之外,您永远不会同时调用FileStream类的方法来遵守它.

In the given code snippet you'll read multiple times from the same position. Move the position update to the BeginRead function. Apart from that you are honoring the contract of the FileStream class by never concurrently calling its methods.

这篇关于使用Stream.BeginRead的顺序异步读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆