Multiple using block, is this code safe?

99封情书 提交于 2021-01-29 03:11:36

问题


Code snippet is as follows

 public static string ToCompressedBase64(this string text)
    {
        using (var memoryStream = new MemoryStream())
        {
            using (var gZipOutputStream = new GZipStream(memoryStream, CompressionMode.Compress))
            {
                using (var streamWriter = new StreamWriter(gZipOutputStream))
                {
                    streamWriter.Write(text);
                }
            }
            return Convert.ToBase64String(memoryStream.ToArray());
        }
    }

As far as I know, if class contains field which is IDisposable then It should implement IDisposable itself and take care of disposal of the owned object, so with this assumptions, after disposal of streamWriter the gZipOutputStream and memoryStream will also be disposed. But we still need not disposed memoryStream to invoke toArray() method on It.
So the question is, Is calling ToArray() method on memoryStream at the end safe?


回答1:


If I understand your question correctly, you are asking if it's safe to call ToArray() on a MemoryStream after it has been disposed.

If so, then yes, it's safe. The documentation specifies:

This method works when the MemoryStream is closed.

EDIT: And in case it's not clear whether closed also means disposed, you can also look at the source code for the Dispose method (Note: The link is to Stream.Dispose() since MemoryStream doesn't override the Dispose method):

public void Dispose()
{
    /* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully.
    Contract.Ensures(CanRead == false);
    Contract.Ensures(CanWrite == false);
    Contract.Ensures(CanSeek == false);
    */

    Close();
}

As you can see, calling Dispose() does nothing more than calling Close().



来源:https://stackoverflow.com/questions/39145436/multiple-using-block-is-this-code-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!