I am a little confused about memory clean up in an ASP.NET application. I had defined several destructors–I know this isn’t the new .NET way of doing things, but I am a creature of habit and I always did it this way in c++– that were working wonderfully in just about every scenario. However, I have noticed that they are sometimes not called in my ASP.NET applications.
I am thinking about implementing IDisposable, but I am under the impression that IDisposable is for other users of your code, and I am not sure that ASP.NET would call Dispose when it is finished with the object. Could someone clarify on this?
What is the best, and by best I mean that it will always work– way to clean up my unmanaged memory?
Edit
This seems to indicate that if the class containing potential unmanaged memory is a member of an encapsulating class, then the destructor is the best strategy. This certainly makes sense to me since I could hardly put a try or a using around a class member. Even then however, that brings me back to my question, it sometimes never gets called in my ASP.NET app.
All classes which handle unmanaged resources should implement the IDisposable interface.
For a little more info, there are two issues with the garbage collector. First, you have no idea when it’s going to run. Second, it has zero knowledge of unmanaged resources.. That’s why they are called unmanaged.
Therefore it’s up to the calling code to properly
disposeof objects that utilize unmanaged resources. The best way to do this is to implement the above interface and either wrap the object in a using ( ) { } statement or, at the least, a try .. finally. I generally prefer the using statement.Also, by implementing IDisposable you are signaling to other developers that this class deals with unmanaged resources so they can take the appropriate steps to ensure things are called correctly.