Reputation: 15097
I'm dealing with my C# program memory usage I set up a memory control between the start and the end of my app to spot memory leaks. I got warning when using Entity Framework 6 with Firebird:
var m = GC.GetTotalMemory(true) / 1024 / 1024; // 2MB
using (Entities context = new Entities(ConnectionString))
{
m = GC.GetTotalMemory(true) / 1024 / 1024; //2MB
context.MYTABLE.FirstOrDefault();
m = GC.GetTotalMemory(true) / 1024 / 1024; // 5MB
}
m = GC.GetTotalMemory(true) / 1024 / 1024; // 5MB ??
By commenting out the context.MYTABLE
line, memory will remain at 2MB.
I know everything will be disposed when the application will end, but I would like to detect memory leaks on my objects and this EF problem prevent that.
Is there a way to dispose this extra memory used by EF?
Could this problem be caused by the Firebird EF driver?
Tia
Upvotes: 0
Views: 2031
Reputation: 23839
Is there a way to dispose this extra memory used by EF?
No - there is no way to release that extra memory in a guaranteed way.
The documentation for GetTotalMemory(true)
states:
Remarks If the forceFullCollection parameter is true, this method waits a short interval before returning while the system collects garbage and finalizes objects. The duration of the interval is an internally specified limit determined by the number of garbage collection cycles completed and the change in the amount of memory recovered between cycles. The garbage collector does not guarantee that all inaccessible memory is collected.
Note in particular the last sentence:
The garbage collector does not guarantee that all inaccessible memory is collected.
On top of this, Entity Framework (and / or Firebird driver) is likely keeping some information cached in RAM for the lifetime of the application. And some of that will likely never be GCed.
Upvotes: 0
Reputation: 249506
There is no reason for the garbage collector to run after you exit the using
block (using only guarantees that the Dispose
method of context
will be called). You can force a garbage collection using GC.Collect()
.
More generally, entities that are loaded using EF will generally live as long as the context they are associated with, unless you manually remove them from the context.
I cannot speak to a memory leak in the Firebird driver for EF, but what you are seeing is expected begaviour.
Upvotes: 3