Asynchronous memory streaming approach: which of the following?

做~自己de王妃 提交于 2019-12-05 10:56:54

The fact is that MemoryStream's Read/WriteAsync methods don't actually provide any kind of true asynchronous implementation. All they do is perform the operation synchronously and return an already completed Task. Therefore there is no benefit to calling the async methods when you know it's a MemoryStream. In fact, it's just completely unnecessary overhead.

Now, forgetting that for a second just to answer your question on style, the first approach is better one because you don't allocate/schedule a new Task unnecessarily (e.g. with Task::Run), but I don't know why you wouldn't just use a using() statement in that approach. So here's the cleanest/simplest IMHO:

private async static Task WriteToStreamFirstVariantSimplified()
{
    using(MemoryStream memoryStream = new MemoryStream())
    {
        byte[] data = new byte[256];

        try
        {
            await memoryStream.WriteAsync(data, 0, data.Length);
        }
        catch(Exception exception)
        {
            //Handling exception
        }
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!