问题描述
如果我知道我正在操作的流是MemoryStream,最好不要使用任何异步方法(CopyToAsync,ReadAsync等)吗?
Is it better to not use any Async methods (CopyToAsync, ReadAsync, etc...) if I know that the stream I'm operating on is a MemoryStream ?
Stephen Clearly对此SO问题的评论让我怀疑我在服务器应用程序中使用的方法,该方法应该能够处理许多并发请求.
A comment of Stephen Clearly on this SO question made me doubt on the approach I'm using in a server-application that should be able to handle many concurrent requests.
在该应用程序中,所有I/O都是异步完成的,因此不会浪费任何线程.但是,似乎CopyToAsync f.i.在MemoryStream上并不是真正异步的,我想知道我是否有任何好处-即使在服务器应用程序中-在MemoryStream上使用异步操作也可以.
In that application, all I/O is done async so that no threads are wasted. However, as it seems that CopyToAsync f.i. is not really asynchronous on a MemoryStream, I wonder if I have any benefit -even in a server-application- to use async operations on a MemoryStream.
推荐答案
好吧,如果您检查 MemoryStream
实现,则会发现 ReadAsync
(和实际上,WriteAsync
是同步的,无需使用任何其他线程.而且虽然有一些开销,但它很小,应该可以忽略不计.
Well, if you check MemoryStream
implementation, you'll find that ReadAsync
(and WriteAsync
) are actually sync without using any additional threads. And while there is some overhead, it's pretty small and should be negligible.
CopyToAsync
是另一种野兽.其他异步方法仅在一个线程上起作用,而 CopyToAsync
在两个线程上起作用.尽管源 MemoryStream
不能从异步中受益,但目标线程却可以.当然,如果两个流都是内存流,您将一无所获.
CopyToAsync
is a different beast. While other async methods works only on one thread, CopyToAsync
works on two. And while your source MemoryStream
doesn't benefit from async, destination thread can. Of course, if both streams are memory streams you won't get any benefit at all.
因此,通常在回答您的问题时, MemoryStream
仅具有异步方法,以便与其他流实现保持一致.但是当您使用它时,不会有任何明显的性能下降.
So, answering your question in general, MemoryStream
have async methods only for consistency with other stream implementations. But you won't get any significant performance degradation when you are using it.
P.S.如果您需要使用 MemoryStream
获得良好的性能,最好避免重新分配,重复使用基础缓冲区等.但这是与异步无关的另一个主题.
P.S. If you need good performance with MemoryStream
, it is better avoid re-allocations, re-use underlying buffers, etc. But it's different topic unrelated to async.
这篇关于我应该在内存流上使用异步I/O吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!