wrapping MemoryStream in a using

前端 未结 6 1988
死守一世寂寞
死守一世寂寞 2020-12-17 19:14

I\'ve been told that System.IO.MemoryStream need not be wrapped in a using block because there is no underlying resource, this kinda goes against what i\'ve always

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-17 19:44

    As Charlie said, it is a recommended practice to Dispose of all objects of classes that implements IDisposable.

    If you look into the implementation of MemoryStream.Dispose(bool) (which is called by Stream.Dispose()), it becomes obvious you should be disposing of it since it updates a few control flags:

    protected override void Dispose(bool disposing)
    {
        try
        {
            if (disposing)
            {
                this._isOpen = false;
                this._writable = false;
                this._expandable = false;
            }
        }
        finally
        {
            base.Dispose(disposing);
        }
    }
    

提交回复
热议问题