Search code examples
c#dispose

Proper and Fastest way to dispose of a large form level object in C#


I understand the basics of using the Dispose/Finalize pattern and I do use it wherever I can but I seem to have a problem with this situation.

I have a very small object:

// Small Object
public class Class1
{
    public int SampleId { get; set; }
}

// Form Level Object
public IList<Class1> MyClasses { get; set; }

MyClasses is populated by loading up to a few thousand of the Class1 objects from the DB. That process works properly.

Because there is no Dispose method on the List<> object and it is using a fair amount of memory I'm unsure of what to do with it. When the user closes the form do I allow the default Close() method to clean up MyClasses, should I use the MyClasses.Clear() to reduce the size of the list in the Dispose method, set MyClasses to null, or possibly something else?

Once the user closes this form they may open the form back up and load another set of data to work with that could be a few thousand in size. Over a few minutes they could be consuming a rather large amount of memory.

I would like to reclaim the memory MyClasses is using fairly quickly so I can reuse it for the next time the user opens the form.

What if Class1 had numerous fields in it making each record considerably larger, would it make a difference as to what methodology I should use to clean up MyClasses?


Solution

  • Short answer: You don't need to worry about trying to reclaim the memory of a List.

    Longer answer: You can read about .NET's garbage collection here. Whenever managed objects (object of a .NET type) are not referenced by any variable anymore, they become subject to the garbage collector. They'll get cleaned up automagically.

    If you're having problems with your app taking too much memory, you're either:

    1. Retrieving more data than you actually need (look for places where you might be retrieving large data sets and filtering in-memory, rather than applying the filtering during retrieval)
    2. You're keeping a reference to old data that you don't need anymore, which prevents the GC from touching it.