In C#, if an exception occurs inside a "using" block, does the Dispose method get called?

有帮助吗?

解决方案

Yes it will get called.

using translates into try-finally block, so even in case of recoverable exception Dispose gets called.

See: using statement C#

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.

Consider SqlConnection which implements IDisposable interface, so the following:

using (SqlConnection conn = new SqlConnection("connectionstring"))
{
    //some work
}

Would get translated into

{
    SqlConnection conn = new SqlConnection("connectionstring");
    try
    {
        //somework
    }
    finally
    {
        if (conn != null)
            ((IDisposable)conn).Dispose(); //conn.Dispose();
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top