2
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. So supposing it threw an exception... Is this a possible memory leak scenario?

4

3 回答 3

6

You're fine. "using" is actually a try..finally in disguise.

于 2012-05-18T19:01:51.040 回答
2

正如 MSDN 所说, C# 编译器将using语句转换为 try-finally 块以确保调用 IDisposable.Dispose():

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

唯一不调用 IDisposable.Dispose() 的情况是在 using 语句块内部调用Environment.FailFast或在 MapDataContainer() 的构造函数内部或之后引发异常时,但这仍然不会阻止垃圾收集器收集这个对象。此外,实现 IDisposable 的对象通常(但不一定)在析构函数中调用 IDisposable.Dispose() 以确保即使程序员忘记手动调用它或将其包装在 using 语句中,也能正确释放任何非托管资源。

于 2012-05-18T19:17:47.173 回答
2

using声明实际上是

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

如您所见,Dispose始终调用 the 。唯一的例外是如果它是 CLR 错误,但在这种情况下,无论如何你都不走运。

于 2012-05-18T19:02:42.087 回答