I’m really looking for some best practice wisdom. So here are the questions, I’ll add more if people leave comments. Feel free to answer some or all of these questions.
When SHOULD I use IDisposable? Only when I have unmanaged resources?
What variations of the dispose pattern are there and why do they vary?
What are common unmanaged resources I should be aware of?
Is it ever wrong or misleading to implement IDisposable?
Should Dispose calls ever be chained together, or should we rely on using statements?
For instance:
public Dispose(bool disposing)
{
...
this.SomeDependency.Dispose;
}
Wow. A lot of questions here!
IDisposableis usually used to clean up resources, but that’s not necessarily all it’s good for. It’s a general pattern to notify the object being consumed that you’re done with it. One example is a timer:In this case, calling
Disposeisn’t necessarily releasing any resources, it’s just a convenient & consistent (two keys for a pattern!) way to tell the timer “OK, I’m done with you now” and the timer can stop timing, and maybe record the time somewhere.Another good rule of thumb is if you need to have a finalizer, for whatever reason, you should usually also provide
IDisposableaccess to the same routine so the consuming class can opt to finalize the class earlier instead of waiting on the GC.There is only one real “specific” type of
IDisposableimplementation I’m aware of – the Finalize/Dispose pattern:Anything that implements
IDisposable, especially in the .NET libraries, should be assumed to have handles to unmanaged resources and should be disposed. Typically you’ll only access unmanaged resources through these. If not, you’ll know – usually building a driver or something.It can be pointless to overuse it, but not directly harmful.
A class should only dispose any IDisposables that it creates internally. If it has disposable dependencies that were injected or live beyond the scope of the class, you should never dispose them.