Question

Hello is there a way to check if a transaction using TransactionScope was committed or rolledback?

Was it helpful?

Solution

The actual Commit is not happening until the TransactionScope is disposed. If the Commit fails for any reason an exception will be thrown. You should Catch that exception and put your logic for failed transaction in the Catch block. If no exception has been thrown you should be assured that Commit was successful. If for any reasons that I cant think of, you don't trust the framework, you can always create another Scope and query the results to make sure they have been applied.

var transactionFailed = false;
try
{
    using (var tx = new TransactionScope())
    {
        tx.Complete();
    }
}
catch (TransactionAbortedException ex)
{
    transactionFailed = true;
    writer.WriteLine("TransactionAbortedException Message: {0}", ex.Message);

}
catch (ApplicationException ex)
{
    transactionFailed = true;
    writer.WriteLine("ApplicationException Message: {0}", ex.Message);
}
catch (Exception ex)
{
    transactionFailed = true;
    writer.WriteLine("Exception Message: {0}", ex.Message);
}

OTHER TIPS

Yes. Just add a variable and check it.

bool txExecuted;

using (var tx = new TransactionScope())
{
 //code
 if (code was OK)
 {
   tx.Complete();
   txExecuted = true;
 }

}

Regarding to msdn documentation https://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.complete(v=vs.110).aspx

// The Complete method commits the transaction. If an exception has been thrown,
// Complete is not called and the transaction is rolled back.

completeCallback method will be call only after sucessfull transactionScope.Complete() method execution

So you can use function:

public bool TryRunTransaction(Action transactionAction)
    {
        try
        {
            using (var transactionScope = new TransactionScope())
            {
                transactionAction();
                transactionScope.Complete();
            }
            return true;
        }
        catch (TransactionAbortedException)
        {
            return false;
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top