As most of us know, in order to manage memory well in .net it is good practice to always call Dispose() on objects that implement IDisposable. However, when writing a lot of code on a daily basis it can be easy to forget to do this.
Does anybody know of a tool that searches through a c# solution and finds all the places where a disposable object hasn't been disposed? I can see there being cases where this doesn't work when object likes bitmaps are assigned to properties but even a more basic checker would have value.
Thanks for your time.
I found that Visual Studio 2010 can do exactly what I was looking for. To get the behaviour do the following:
Add the following rules to your rules set:
Or just run them as part of your general code analysis rules. It won't catch everything but its a better safety net than no safety net.
My favorite memory profiler is Ants Profiler from Redgate. It's pretty simple to use, and they have lots of tutorials to get you started. Best thing is the 14 day free trial, so you can try it out and make sure it's going to work for you before you buy it.
Assuming that you're using the recommended pattern of suppressing finalization when Dispose is invoked manually, you can spot these errors is by adding a bit of code to tell you whenever Dispose is invoked on the finalizer thread.
~MyClass()
{
Dispose( false );
Console.WriteLine( "Argh, release me! I want better co-workers!" );
}
public Dispose()
{
Dispose( true );
GC.SuppressFinalization( this );
}
public Dispose( bool invokedByDeveloper )
{
if( invokedByDeveloper )
// free managed resources
// free unmanaged resources
}
Using a memory profiler as suggested by BrandonZeider is also an option. ANTS is a great, albeit somewhat pricey, profiler. Jetbrains also make a good profiler, and you can try both for 30 days without buying.
Probably the best way to stop a problem like this in its tracks is to be disposed "obsessed". Think about being efficient by doing things like planning when and where in your code your objects can be disposed, and then dispose them. If you work in a team, bring up disposal to them.
If the scope of your disposable object is short lived and maybe contained in one small part of a method somewhere, wrap it with a using so it's guaranteed to be disposed. I use using (is that grammatically correct?) any chance I get.
Obviously these aren't automated suggestions and won't always work but it's not hard to be in the right mindset and learn best practices that you can apply to everyday work. That's my two cents.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With