Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leak when using Entity Framework

Tags:

I have a very simple application using EF. But when it runs a week, the memory usage is awful (only 80MB at first, 700MB after one week). When I use dotMemory to profile my application. I find the memory of Heap generation 2 is increasing all the time.

only run 40 minutes

I Get a snapshot, finally find the retained bytes of ef dbcontext is the most.

enter image description here

I am so confused. My application is so simple. Code sample:

protected CarbonBrushMonitorEntities _entities = new MYEntities(); public void Add(HistoryData data) {    _entities.HistoryDatas.Add(data);    _entities.SaveChanges(); }   

_entities only initials once at the starting time, then used all the time.

The function Add is frequently called,about 3 times/second

I google a long time, and try some methods such as:

_entities.Configuration.ValidateOnSaveEnabled = false; _entities.Configuration.AutoDetectChangesEnabled = false; _entities.Configuration.LazyLoadingEnabled = false; 

but these do not work.

like image 498
yubaolee Avatar asked May 13 '15 08:05

yubaolee


1 Answers

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.

like image 102
L-Four Avatar answered Oct 10 '22 13:10

L-Four