MiBol
MiBol

Reputation: 2125

How keep the memory clear in the C# applications (DataTable dispose)?

What's the best way to dispose a DataTable and clear all RAM memory related in the C# application?

I have a simple code:

private void Form1_Load(object sender, EventArgs e)
{
    using (DataTable vDT = new DataTable())
    using (DataTable vDTsec = new DataTable())
    {
        vDT.Columns.Add("A");
        vDT.Columns.Add("B");
        vDT.Columns.Add("B_1");

        vDTsec.Columns.Add("A");
        vDTsec.Columns.Add("B");
        vDTsec.Columns.Add("E");

        for (int x = 1; x <= 1000000; x++)
        {
            vDT.Rows.Add(new object[] { x, "B" + x.ToString(), "C" + x.ToString() });
            vDTsec.Rows.Add(new object[] { x, "B" + x.ToString(), "E" + x.ToString() });
        }

        vDT.Dispose();
        vDTsec.Dispose();
    }

    GC.Collect();
    GC.WaitForFullGCApproach(100);
    GC.WaitForPendingFinalizers();
}

If I put a breakpoint before to create the million of rows the application has a size of ~4MB: 1aa

After the creation of all rows, the memory has a huge increase (~428MB): 2aa

Even after to dispose the both tables, the memory continues in ~428MB: 3aa

How I can free this memory from the program?

Upvotes: 1

Views: 3594

Answers (2)

Dave Ranck
Dave Ranck

Reputation: 1

You should not normally invoke garbage collection yourself. Call Dispose() and let GC do it's thing. GC.Collect() tries to collect all generations. GC is or can be expensive. Most of the time it handles itself well and we do not need to get directly involved.

Make sure unmanaged objects are explicitly closed and/or disposed of (like DB connections). If you are loading that much data into a datatable in memory that you feel the need to force a collection, you might want rethink your approach. I'd be interested in understanding what you are doing that would require a GC.

Upvotes: 0

Robert Harvey
Robert Harvey

Reputation: 180788

First, you shouldn't necessarily be concerned about that number you see in Task Manager. All that means is that the Garbage Collector hasn't collected the memory yet (or the OS is caching the memory), and if the OS doesn't need it, the GC may wait awhile to collect it.

The only compelling reason to better control the memory usage (beyond sensible object management) in your application is to improve your program's performance characteristics. The way you do that is by using Object Pooling, which basically means that, instead of destroying and recreating objects, you create them once, and then reuse them, so the GC never collects. But only use this if you've exhausted all other techniques for improving performance.

Upvotes: 3

Related Questions