Should I use async I/O on memorystreams?

2019-08-23 03:27发布

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 ?

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.

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.

1条回答
Lonely孤独者°
2楼-- · 2019-08-23 04:09

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 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.

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. 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.

查看更多
登录 后发表回答