简体   繁体   English

在这个c#EF场景中我是否需要担心垃圾收集?

[英]Do I have to worry about garbage collection in this c# EF scenario?

try
{
  using (MapDataContainer ent = new MapDataContainer()) //is an autogen'd EF object
  {
     //do some stuff, assume it throws an error
  }
}
catch(Exception ex) //catching outside using not sure if IDispose called
{
  //handle error
}

Normally I understand that the using called the IDispose on the EF object. 通常我理解在EF对象上使用称为IDispose。 So supposing it threw an exception... Is this a possible memory leak scenario? 所以假设它抛出一个异常......这是一个可能的内存泄漏情况吗?

You're fine. 你没事。 "using" is actually a try..finally in disguise. “使用”实际上是一种尝试......最终是伪装。

The using statement is actually 实际上是using语句

ResourceType resource = expression;
try {
   statement;
}
finally {
   if (resource != null) ((IDisposable)resource).Dispose();
}

So as you can see, the Dispose is always called. 如您所见, Dispose始终被调用。 The only exception is if it is a CLR error, but in that case you're out of luck anyway. 唯一的例外是如果它是CLR错误,但在这种情况下你还是运气不好。

As MSDN says, using statement is translated by C# compiler to try-finally block to ensure, that IDisposable.Dispose() is called: 正如MSDN所说, using语句由C#编译器翻译为try-finally阻止以确保调用IDisposable.Dispose():

{
  MapDataContainer ent = new MapDataContainer();
  try
  {
    ...
  }
  finally
  {
    if (ent != null)
      ((IDisposable)ent).Dispose();
  }
}

The only cases when IDisposable.Dispose() is not called is when Environment.FailFast is called inside using statement block or when exception is thrown inside or right after the constructor of MapDataContainer(), but this still doesn't prevent Garbage collector to collect this object. 不调用IDisposable.Dispose()的唯一情况是使用语句块在内部调用Environment.FailFast时,或者在MapDataContainer()的构造函数内部或后面抛出异常时,但这仍然不能阻止垃圾收集器收集这个对象。 Additionally objects that implements IDisposable typically (but not necessarily) call IDisposable.Dispose() in destructor to ensure that any unmanaged resources will be correctly released even in programmer forgets to call it manually or wrap it in using statement. 另外,实现IDisposable的对象通常(但不一定)在析构函数中调用IDisposable.Dispose(),以确保即使在程序员中忘记任何非托管资源也会忘记手动调用它或将其包装在using语句中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM