Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I ensure that objects are disposed of properly in .NET?

Tags:

c#

.net

I have created a Windows Forms application in .NET 2 using C# that runs continuously. For most accounts I am pleased with it, but it has been reported to me that it has failed occasionally. I am able to monitor its performance for 50% of the time and I have never noticed a failure.

At this point I am concerned that perhaps the program is using too many resources and is not disposing of resources when they are no longer required.

What are the best practices for properly disposing created objects that have created timers and graphical objects like graphics paths, SQL connections, etc. or can I rely on the dispose method to take care of all garbage collection?

Also: Is there a way that I could monitor resources used by the application?

like image 748
Brad Avatar asked May 02 '09 12:05

Brad


Video Answer


2 Answers

Best practice is to make sure that all objects implementing the IDisposable interface is called Dispose on as soon as the object is no longer required.

This can be accomplished either with the using keyword or try/finally constructs.

Within a WinForms form that has resources allocated for the lifetime of the form, a somewhat different approach is necessary. Since the form itself implements IDisposable this is an indication that at some point in time Dispose will be called on this form. You want to make sure that your disposable resources gets disposed at the same time. To do this you should override the forms Dispose(bool disposing) method. The implementation should look something like this:

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        // dispose managed resources here
    }
    // dispose unmanaged resources here
}

A note on Components in forms: if your object implements the IComponent interface you can place the instance in the forms Container. The container will take care of disposing components when the container itself is disposed.

like image 128
Peter Lillevold Avatar answered Oct 21 '22 14:10

Peter Lillevold


In addition to what's already been said, if you're using COM components it's a very good idea to make sure that they are fully released. I have a snippet that I use all the time for COM releases:

private void ReleaseCOMObject(object o)
{
   Int32 countDown = 1;
   while(countDown > 0)
       countDown = System.Runtime.InteropServices.Marshal.ReleaseCOMObject(o);
}
like image 29
AJ. Avatar answered Oct 21 '22 12:10

AJ.