简体   繁体   English

.Net System.IO.Stream异步/非阻塞

[英].Net System.IO.Stream async/nonblocking

I'm wanting to wrap an external resource and convert it into a stream in my application (to be then consumed by PushStreamContent in a webapi controller). 我想换一个外部资源,并将其转换成流在我的应用程序(被然后通过消耗PushStreamContent中的WebAPI控制器)。

The documentation for Streams in C# doesn't really infer how I can create one that uses the async methodology. C#中Streams的文档并没有真正推断出如何创建使用异步方法的文档。

Eg trying to inherit from System.IO.Stream gives a very syncrhonous looking "Read" method. 例如,尝试从System.IO.Stream继承会产生一个非常同步的“读取”方法。 Ideally I would want my read to be a task that is "awaitable". 理想情况下,我希望我的阅读是一项“可等待的”任务。 Even the readAsync methods look like they expect read to be synchronous, they just get to choose the chunks. 即使readAsync方法看起来像他们希望读取是同步的一样,他们也只能选择块。

I very want something like select in C, where I can set IO to be ready to read and then the readAsync stuff would continue reading. 我非常想要类似C中的select之类的东西,在这里我可以将IO设置为可以读取,然后将继续读取readAsync内容。 There may be points where there is data pending externally, so I would like the read call to defer to other tasks and continue reading when it is ready. 可能有些地方有外部待处理的数据,因此我希望read调用可以推迟到其他任务,并在准备就绪时继续读取。

public override int Read(byte[] buffer, int offset, int count)
{
    throw new NotImplementedException();
}

Should I be explicitly overriding ReadAsync to accomplish this?. 我是否应该显式重写ReadAsync来完成此操作? Is there any documentation around on how to implement your own streams in .NET 是否有有关如何在.NET中实现自己的流的文档?

The basis of a readable Stream is the synchronous Read operation. 可读Stream的基础是同步Read操作。 The Stream class implements ReadAsync around the synchronous Read so you don't need to rewrite ReadAsync . Stream类围绕同步Read实现ReadAsync ,因此您无需重写ReadAsync

If the default implementation is not sufficient (such as, there are some smarts you want to inject into the asynchronous code or some performance improvements based on the internal implementation of the resource you are streaming) then you can override the BeginRead and EndRead methods. 如果默认实现还不够(例如,您需要将一些智能注入异步代码中,或者基于要流传输的资源的内部实现来进行一些性能改进),则可以覆盖BeginReadEndRead方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM