Do I need to call dispose in the finally block for SqlTransaction? Pretend the developer didnt use USING anywhere, and just try/catch.
SqlTransaction sqlTrans = con.BeginTransaction();
try
{
//Do Work
sqlTrans.Commit()
}
catch (Exception ex)
{
sqlTrans.Rollback();
}
finally
{
sqlTrans.Dispose();
con.Dispose();
}
It does not hurt to have it. This is true for every class implementing IDisposable, otherwise it would not implement this interface.
But normally the garbage collector deals with unreferenced objects(it doesn’t mean that the GC calls dispose, which isn’t true), so you need it only for unmanaged resources. But because i also don’t want to call
disposeon every other variable or use the using-statement everywhere, it it’s always worth to look into the actual implementation of the class’Disposemethod.SqlTransaction.Dispose:Without understanding all(or anything) what is happening here i can say that this is more than a simple
base.Dispose(disposing). So it might be a good idea to ensure that a SqlTransaction gets disposed.But because
SqlConnection.BeginTransactioncreates the transaction it could also be a good idea to reflect this also:As you can see. The GC will also keep the Connection alive when a Transaction is created. It also doesn’t hold a reference to the transaction since it only returns it. Hence it might not be disposed even when the connection is already disposed. Another argument to dispose the transaction.
You might also have a look at the
TransactionScopeclass which is more fail-safe thanBeginTransaction. Have a look at this question for more informations.