实体框架内存泄漏

时间:2016-04-02 07:34:45

标签: c# entity-framework memory-leaks

我通过dotMemory JetBrains监控软件内存的消耗。

我注意到当我通过我的存储库进行查询时,如果我关闭窗口,我就离开了我打电话的对象;我的存储库进入内存,我使用甚至处理我的上下文但在内存中没有任何东西。我可以检查什么?

以下是有问题的代码:

LoginViewModel.cs

using (DbContext = new Context())
{
   var creazioneDocumentoRepository = new RepositoryBase<CreazioneDocumento>(ctx);
   var creazioneDocumento = creazioneDocumentoRepository.Lista();

   if (creazioneDocumento == null || creazioneDocumento.Count == 0) 
      return;

   var decimaliQuantita = creazioneDocumento.Max(x => x.NumeroDecimaliQuantita);
   _NumeroDecimaliQuantita = decimaliQuantita != 0 && decimaliQuantita > 0 ? decimaliQuantita : 0;

   var decimaliPrezzo = creazioneDocumento.Max(x => x.NumeroDecimaliPrezzo);
   _NumeroDecimaliPrezzo = decimaliPrezzo != 0 && decimaliPrezzo > 0 ? decimaliPrezzo : 3;
   _NumeroDecimaliImponibile = 2;

   //   ctx.Dispose();
}

做调试,我注意到了:

if (creazioneDocumento == null || creazioneDocumento.Count == 0) return;

对象不会被记住,但只要我运行“max”,对象就会保留在内存中。

以下是dotmemory的截图:

enter image description here

相反,这个屏幕截图告诉我哪些方法引用并保留在我的loginviewmodel内存中,我相信它们是最大的两个:

enter image description here

1 个答案:

答案 0 :(得分:0)

.NET CLR是一个托管的,垃圾收集的运行时/虚拟机。

您不能指望一旦不需要对象就会被回收并从内存中删除。

另一方面,IDisposable.Dispose只是定义代码以释放实现所使用的底层资源的接口方法:它不是释放内存的内置方法。

垃圾收集器(GC)将内存回收为后台进程,它不会立即删除任何内容,但会基于超时的假设。

进一步阅读:Understanding garbage collection in .NET