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.
I Get a snapshot, finally find the retained bytes of ef dbcontext is the most.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With