This question is related to my question: SQL Server and TransactionScope (with MSDTC): Sporadically can't get connection
I'm doing some transaction programming using the .net TransactionScope
class. If I understand correctly, I can do some SQL operations within a transaction by wrapping the SQL calls inside a using ts as new TransactionScope()
block, or by using new TransactionScope()
and then TransactionScope.Dispose()
at the end.
To commit the transaction, MSDN says to use TransactionScope.Commit()
. Supposing that I want to rollback the transaction under certain circumstances, is it sufficient to simply call TransactionScope.Dispose()
without calling the Commit method first? Is that good practice, or is this supposed to be done some other way?
if you know you want to rollback then do that explicitly. You are not guaranteed that Dispose will rollback (in the case where complete has been called, the transaction will be committed when you call Dispose)
to your question about using or new/Dispose they are not equivalent
using(var ts = new TransactionScope())
{
}
is equivalent to
TransactionScope ts;
try
{
ts = new TransactionScope();
}
finally
{
ts.Dispose();
}
to answer your follow up question no if you call Dispose you will not have your transaction "hanging around" it will either commit or rollback. However if you use the new/dispose as you wrote it (no finally block) you can have a situation where dispose isn't called when you expect it to be (in the case of an exception)