Method returns an IDisposable - Should I dispose of the result, even if it's not assigned to anything?

前端 未结 4 1996
轻奢々
轻奢々 2021-01-13 05:08

This seems like a fairly straightforward question, but I couldn\'t find this particular use-case after some searching around.

Suppose I have a simple method that,

4条回答
  •  梦谈多话
    2021-01-13 06:10

    Yes, you should definitely dispose of the FileStream. Otherwise the stream will remain open and the file won't be usable until a finalizer happens to clean it up.

    The important thing here is ownership: for File.Open, the caller is assumed to "own" the stream returned to it - and if you own something which implements IDisposable, it's your responsibility to dispose of it.

    Compare this with the situation of Image.FromStream: in that case, you pass in a stream and the Image then assumes that it owns that stream. You mustn't close the stream yourself, in that case - you have to dispose of the image when you're done, and it will dispose of the stream.

    Calling a static method which returns something disposable almost always assumes that the caller takes ownership of the resource. Ditto constructors (which are effectively static methods.)

    The irony in this case is that if you don't dispose of the stream returned by File.Open, you'll have found that the file is usable - at the same time as making it unusable until some indeterminate time.

提交回复
热议问题