【发布时间】:2015-01-01 11:09:02
【问题描述】:
目前我正在优化一个大型批处理程序的内存使用。不同的数据表使用最多的内存。例如,我的 DataTable dataTable 使用了大约 260MB。
就像线程“What is the memory overhead of storing data in a .NET DataTable?”的已接受答案中的建议一样,我正在尝试将相关数据移出 DataTable。这是我的代码:
GC.Collect(); // force the garbage collector to free memory
// First stop point - Total process memory (taskmanager) = 900 MB
List<ExpandoObject> expandoList = new List<ExpandoObject>();
foreach (DataRow dataRow in dataTable.Rows)
{
dynamic expandoItem = new ExpandoObject();
expandoItem.FieldName = dataRow["FieldName"].ToString();
expandoList.Add(expandoItem);
}
// Second stop point - Total process memory (taskmanager) = 1055 MB
dataTable.Clear();
dataTable.Dispose();
dataTable = null;
GC.Collect(); // force the garbage collector to free memory
// Third stop point - Total process memory (taskmanager) = 1081 MB (wtf? even more!)
我正在使用 Clear、Dispose 并设置为 null,因为它在以下线程中被建议:Datatable.Dispose() will make it remove from memory?
查看停止点 cmets 以查看该点的内存使用情况。我也试过using (DataTable dataTable = ...),但结果是一样的。
我做错了什么? 也许有更好的方法来缩小 DataTable 中的数据?
【问题讨论】:
-
运行内存分析器并查看您的数据表(或其他任何大型数据表)是否仍在被引用。
-
dtTest 从何而来?它是方法调用的参数吗?如果是这样,它仍然会被调用方法引用,因此它不符合垃圾回收的条件。
-
它来自同一个函数。问题是我使用任务管理器检查内存大小。我不知道.NET中有保留内存。
标签: c# memory datatable memory-optimization