开发者

Is IDisposeable Called if Un-Handled Exception is Encountered in a Using Statement?

If I have the following, will IDisposeable still be called on DisposeableObject, or will the object remain opened because an un-handled exception is encountered?

using ( DisposeableObject = new Object() )
{
   thro开发者_JAVA百科w new Exception("test");
}


A using is like wrapping your code in a try...finally and disposing in the finally, so yes, it should be called.


using expands to a try..finally block, so yes, it will call Dispose.


In the example you provided Dispose will be called before the exception is thrown.

The normal code for ensuring that dispose gets called looks like

var connection= new SqlConnection(connectionString);
try
{
  // do something with the connection here
}
finally
{
  connection.Dispose();
}

The usings statement replaces the need to write such a cumbersome statement.

using(var connection = new SqlConnection(connectionString))
{
  // do something with the connection here
}


According to MSDN, yes. When control leaves the scope of the using statement, expect it to be disposed.


The object will be disposed as you will come out of scope when the exception bubbles up.

See: using Statement (C# Reference)

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜