Mubashir Khan
Mubashir Khan

Reputation: 1494

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 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();
                    }
                }

Upvotes: 3

Views: 5558

Answers (3)

Mubashir Khan
Mubashir Khan

Reputation: 1494

[STAThread] on the Main function was causing problem. Removed it and everything is working fine now.

Upvotes: 0

Joe Mancuso
Joe Mancuso

Reputation: 2129

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.

Upvotes: 0

CharithJ
CharithJ

Reputation: 47530

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.

Upvotes: 4

Related Questions