DataTable memory leak
following piece of code is leaking memory even if no data is returned by database. could anyone shed some light on this. .net 开发者_C百科profiler application shows that the culprit is datatable
using (OleDbDataAdapter da = new OleDbDataAdapter("select * from external_message where status='P' and pendingthread=" + Thread.CurrentThread.ManagedThreadId, conn))
{
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
NotificationService.Logger.Write(Logger.RdvLogLevel.Debug, (uint)Thread.CurrentThread.ManagedThreadId, "GetInputs", "Received Message Id {0} Type {1}", dr["MessageId"].ToString(), dr.Field<string>("TargetType"));
return new DatabaseItem { connection = conn, dataRow = dr };
}
else
{
dt.Dispose();
}
}
Probably below line cause memory leak. You have to Dispose Database Connections which holds some unmanaged data.
return new DatabaseItem { connection = conn, dataRow = dr };
If it leaking memory even if no data is return make sure you Dispose conn
? Always you have to dispose database connections.
I don't think that it is a leak. Such objects will consume resources until they are garbage collected. Your dt.Dispose() will provide a hint to the garbage collector that your object is no longer needed, but .Net will not clean it up until it feels like it.
You can prompt the garbage collector to run by calling GC.Collect(), but normally you should let .Net clean up after itself.
[STAThread] on the Main function was causing problem. Removed it and everything is working fine now.
精彩评论