使用实体框架时发生内存泄漏 [英] Memory leak when using Entity Framework
问题描述
我有一个使用EF的非常简单的应用程序。但是当它运行一周时,内存使用情况非常糟糕(最初只有80MB,一个星期后只有700MB)。
当我使用dotMemory来分析我的应用程序时。我发现第2代堆的内存一直在增加。
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.
我得到一个快照,最后找到ef dbcontext保留的字节最多。
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
仅缩写
函数 Add
经常被调用,大约3次。 / second
The function Add
is frequently called,about 3 times/second
我在Google上搜索了很长时间,请尝试以下方法:
I google a long time, and try some methods such as:
_entities.Configuration.ValidateOnSaveEnabled = false;
_entities.Configuration.AutoDetectChangesEnabled = false;
_entities.Configuration.LazyLoadingEnabled = false;
但这些方法不起作用。
推荐答案
如果使用实体框架,则应在需要上下文之前创建上下文,并尽快将其放置:
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.
我通常要做的是向IoC容器注册上下文:
What I typically do is register the context with an IoC container:
DependencyFactory.RegisterType(typeof(SomeContext));
并使用上下文解析器(当然也已向IoC注册):
and use a context resolver (also registered with IoC of course) like:
using (var someContext = _contextResolver.ResolveContext())
{
// your commands/queries
}
其中的解析度如下:
public class ContextResolver : IContextResolver
{
public ISomeContext ResolveContext()
{
return DependencyFactory.Resolve<SomeContext>();
}
}
EF上下文实际上是您的工作单元,一旦您不再需要,则应将其丢弃。
The EF context is actually your unit of work, which should be disposed of once you don't need it anymore.
这篇关于使用实体框架时发生内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!