数据表内存泄漏
即使数据库没有返回数据,以下代码也会泄漏内存。谁能解释一下这一点。 .net profiler 应用程序显示罪魁祸首是数据表
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();
}
}
following piece of code is leaking memory even if no data is returned by database. could anyone shed some light on this. .net 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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可能低于线导致内存泄漏。您必须处置保存一些非托管数据的数据库连接。
如果即使没有返回数据也会泄漏内存,请确保您处置
conn
?您始终必须处理数据库连接。Probably below line cause memory leak. You have to Dispose Database Connections which holds some unmanaged data.
If it leaking memory even if no data is return make sure you Dispose
conn
? Always you have to dispose database connections.我不认为这是泄漏。这些对象将消耗资源,直到它们被垃圾收集。您的 dt.Dispose() 将为垃圾收集器提供一个提示,表明您的对象不再需要,但 .Net 不会清理它,直到它感觉需要为止。
您可以通过调用 GC.Collect() 来提示垃圾收集器运行,但通常您应该让 .Net 自行清理。
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.
Main 函数上的 [STAThread] 导致了问题。删除它,现在一切正常。
[STAThread] on the Main function was causing problem. Removed it and everything is working fine now.