Johan Karlsson
Johan Karlsson

Reputation: 928

Determining if a TransactionScope is committed or not

Using .net 2 and ADO.NET.

Is there a way to determine if a transaction is committed or not? The reason is that I'm stuck with a legacy framework that I cannot alter and there might or might not be an ambient transaction. Sometimes the ambient transaction is already committed causing the next database call to throw an exception and I need to know if it is or not.

Any pointers would be great!

Thanks

Johan

Upvotes: 2

Views: 1410

Answers (2)

BLoB
BLoB

Reputation: 9725

The best method I've found for capturing this most efficiently / correctly is as follows:

Inside the transactionscope using statement, and before the call to scope/Complete().

//Register for the transaction completed event for the current transaction
Transaction.Current.TransactionCompleted += new TransactionCompletedEventHandler(Current_TransactionCompleted);

Then create the event handler function as follows:

/// <summary>
/// Handles the TransactionCompleted event of the Current control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Transactions.TransactionEventArgs"/> instance containing the event data.</param>
static void Current_TransactionCompleted(object sender, TransactionEventArgs e)
{
    if (e.Transaction.TransactionInformation.Status == TransactionStatus.Committed)
    {
        /// Yay it's committed code goes here!
    }
}

To quote MSDN

"You can register for this event instead of using a volatile enlistment to get outcome information for transactions. The parameter passed to the TransactionCompletedEventHandler delegate is a Transaction instance. You can then query the TransactionInformation property of the specific instance to get an instance of TransactionInformation, whose Status property contains the status of a transaction with either the Committed or Aborted value."

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Check Transaction.Current.TransactionInformation.Status. If it is anything other than TransactionStatus.Active, you should not be using the current transaction.

It goes without saying that you should check Transaction.Current for null before taking its status.

Upvotes: 3

Related Questions