Link to home
Start Free TrialLog in
Avatar of cartti
cartti

asked on

DataTable - memory leak

I have code that copies the structure and contents of a DataTable into another DataTable object. The problem I'm having is, everytime the code is run, memory for the application according to Task Manager creeps up by a meg. The code I'm using is:

...
dt_temp = GetCopiedDataTable(m_tblStatic);
...


private DataTable GetCopiedDataTable(DataTable source)
{
        DataTable dt = source.Clone();
                for (int i = 0; i<source.Rows.Count;i++)
                {
                          dt.ImportRow(source.Rows[i]);
                }
        return dt;
}

I was under the impression that if dt_temp is reassigned, the garbage collection would release resources that used for the previous reference. However, it doesn't release any memory at all. Any ideas?
Avatar of c_myers
c_myers

1.) Is dt_temp part of a DataSet? If so, then the DataSet still has a reference to the table, and the GC can't free it.
2.) Is dt_temp referenced anywhere else? If so, those other references are keeping it alive.

Also, using TaskManager as a guage for memory consumption is folly. You should be using the performance counters in PerfMon.

Also, the CLR will continue to increase its working set and not lower it (even though the memory is getting freed) until the system is in a low memory state, or Windows specifically tells the CLR to back off.

If you have 1GB of ram and using 128MB of it, why should the CLR spend a bunch of time rearranging the working set size (an expensive operation) when it doesn't have to?

If you're really concerned about it, you can call the Win32 API function SetWorkingSetSize, but I would do some research on this before doing it, because you CAN do some harm to your process because now you're essentially fighting with the GC and the CLR memory subsystem.
Avatar of cartti

ASKER

Thanks c_myers for your in depth response...

dt_temp is a DataTable. It is assigned to the DataSource property of a DataGrid object. That is its only reference. If the routine is called again, I would have thought the memory would be freed up if the DataSource was reassigned, but it never is - it just grows. I will check out alternative memory consumption utilities in the meantime.

Thanks...
Avatar of Bob Learned
Did you try DataTable.Copy?

Bob
How do you create the datatable?

Is it:

DataTable dt_temp = new DataTable()?

If that's the case, and then you assign it as the data source to a grid (is this ASP.NET or WinForms?), and then, later, re-assign it to something else, you're right, the original dt_temp ref should be flagged for garbage collection.
ASKER CERTIFIED SOLUTION
Avatar of TheAvenger
TheAvenger
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial