I am working on a large project, and one of my tasks is to remove possible memory leaks. In my code, I have noticed several IDisposable items not being disposed of, and have fixed that. However, that leads me to a more basic question, how do I find all classes used in my project that implement IDisposable? (Not custom-created classes but standard Library classes that have been used).
I have already found one less-than-obvious class that implements IDisposable ( DataTable implements MarshalByValueComponent, which inherits IDisposable). Right now, I am manually checking any suspected classes by using MSDN, but isn't there some way through which I can automate this process?
If a type implements the IDisposable interface, you should always call the Dispose method on an instance of the class when you are done using it. The presence of IDisposable indicates that the class has some resources that can be released prior to garbage collection.
You should implement IDisposable when your class holds resources that you want to release when you are finished using them. Show activity on this post. When your class contains unmanaged objects, resources, opened files or database objects, you need to implement IDisposable .
IDisposable is defined in the System namespace. It provides a mechanism for releasing unmanaged resources. When your application or class library encapsulates unmanaged resources such as files, fonts, streams, database connections, etc, they should implement the IDisposable interface or the IAsyncDisposable interface.
Typically, types that use unmanaged resources implement the IDisposable or IAsyncDisposable interface to allow the unmanaged resources to be reclaimed. When you finish using an object that implements IDisposable, you call the object's Dispose or DisposeAsync implementation to explicitly perform cleanup.
Reflector can show you which classes implement IDisposable
: just locate the IDisposable
interface in Reflector, and expand the "Derived types" node
Another option, from code, is to scan all loaded assemblies for types implementing IDisposable
:
var disposableTypes =
from a in AppDomain.CurrentDomain.GetAssemblies()
from t in a.GetTypes()
where typeof(IDisposable).IsAssignableFrom(t)
select t;
Test your project with FxCop. It can catch all places where IDisposable objects are not disposed. You may need to do some work to disable all irrelevant FxCop rules, leaving only IDisposable-related rules.
For example, this is one of FxCop IDisposable rules: http://msdn.microsoft.com/en-us/library/ms182289%28VS.100%29.aspx
Note: you need to find both your own, .NET and third-party IDisposable objects which are not handled correctly.
You can use NDepend to analyze your project and find all types that implement IDisposable.
Here´s the the cql query for the result
SELECT TYPES WHERE Implement "System.IDisposable"
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