Memory leak when using Entity Framework
If you use entity framework, you should create the context just before you need it and dispose it as soon as possible:
using (var someContext = new SomeContext())
{
// your commands/queries
}
Never keep context in memory or share it across different calls.
What I typically do is register the context with an IoC container:
DependencyFactory.RegisterType(typeof(SomeContext));
and use a context resolver (also registered with IoC of course) like:
using (var someContext = _contextResolver.ResolveContext())
{
// your commands/queries
}
where resolution is done like:
public class ContextResolver : IContextResolver
{
public ISomeContext ResolveContext()
{
return DependencyFactory.Resolve<SomeContext>();
}
}
The EF context is actually your unit of work, which should be disposed of once you don't need it anymore.
The other way is to clear the changetracker of the respective entities of concern or even
of all the entities. This is done by changing the entity state to "Detached". This called after dbContext.SaveChangesAsync()
protected void DisposeDbset<T>() where T : class
{
var Tname = typeof(T).Name;
var changetrackercollection = _unitOfWork.dbContext.ChangeTracker.Entries<T>();
foreach (var item in changetrackercollection.ToList())
{
item.State = EntityState.Detached;
}
GC.Collect();
}
I recently faced a similar situation where I was inserting 3,00,000 rows in batch operation. After inserting the rows, the change tracking info for all the rows remained in the memory with the entity state as Unchanged. Hence after every SaveChangesAsync()
call, the changetracker accumulated.
I could not resolve new instance dbcontext for every batch, as it was a more expensive operation.
Just FYI, i had configured dbConetext.ChangeTracker.QueryTrackingBehavior = NoTracking
. But this is applicable to while fetching the data.
Hopefully this is helpful. I found my solution with the help of this link http://andreyzavadskiy.com/2016/09/23/entries-in-entity-framework-changetracker-could-degrade-database-write-performance/?unapproved=19301&moderation-hash=4acc61a32ead7232959c2ec1ca268180#comment-19301