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

前端 未结 4 1964
轻奢々
轻奢々 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:06

    If a method returns an IDisposable, I personally would always put it in a using block. Even if I don't assign the return value to anything.

    Even if you don't assign it to a variable, the disposable object is still created. Dispose is not going to be called automatically. The only difference will be that the returned object will become immediately eligible for garbage collection, because there are no (strong) references to it.

    The garbage collector does not call Dispose automatically when it reclaims an object. However, most IDisposable types provide a finalizer (which will be called just before the GC reclaims an object) that invokes Dispose as a fallback strategy (safety net) — study the IDisposable pattern to see how this is done:

    ~SomeClass          // <-- the finalizer method will usually call Dispose;
    {                   //     but you have no control over when it will be called!
        Dispose(false);
    }
    

    Remember that you don't know when the garbage collector will run (because it's non-deterministic). Therefore, you also don't know when the finalizer method will be called. And because of that -- if you haven't called Dispose explicitly (either yourself, or with a using block) -- you don't know when it will be called by the finalizer.

    That's the advantage of calling Dispose explicitly: You can free resources -- or at least allow the GC to free managed resources -- as soon as you're done with them, instead of holding on to resources until the finalizer gets called sometime in the future.

提交回复
热议问题