If I have a connection in a using statement, will the connection be closed if an exception occurs in the using statement?

StackOverflow https://stackoverflow.com/questions/23231504

The following code doesn't have any sort of error handling.

I'm curious though. As it sits, will the connection that is created in the using statement be closed when the exception is thrown? Or will the connection remain open because it was never explicitly closed?

public override string ResetToDefault() {
    string result;
    using (var cn = HostFacade.GetDbConnection())
    {
        cn.Open();
        DbProvider.Transaction = cn.BeginTransaction();

        // Do something here that throws an unhandled exception.

        DbProvider.Transaction.Commit();
        cn.Close();
    }
    return result;
}

Edit: The connection being returned by HostFacade.GetDbConnection is an IDbConnection. It's safe here to assume it's being implemented as a SqlConnection object.

有帮助吗?

解决方案

Yes, because a using statement is expanded by the compiler to be a try...finally block. Your code is the same as this:

SqlConnection cn = null;

try {
    cn = HostFacade.GetDbConnection();
    cn.Open();
    // .. rest of the code here
}
finally {
    if (cn != null)
        cn.Dispose();
}

The Dispose call will close the connection.

The CLR guarantees that a finally block will execute.. except in very specific scenarios (such as a call to FailFast IIRC).

其他提示

It depends on the implementation of Dispose() by the author of the specific library you are running.

Libraries built into the .NET Framework (like your example) will undoubtedly clean up the resources accessed, like the SqlConnection, but you should verify with documentation first, before assuming anything.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top