Sdílet prostřednictvím


Transaction Rollback

This topic applies to Windows Workflow Foundation 4 (WF4).

This sample shows how to create a custom NativeActivity that accesses the ambient RuntimeTransactionHandle to get the ambient transaction and explicitly roll it back.

Sample Details

In workflow, a transaction is automatically completed when the outermost TransactionScope or TransactedReceiveScope completes. A transaction implicitly rolls back when an unhandled exception propagates across the scope boundary. However, there may be times when it makes sense to explicitly roll back a transaction without having to throw an exception. In this case, you can use the custom rollback activity like the one in this sample to explicitly abort the ambient transaction and provide an optional exception reason.

The RollbackActivity is a NativeActivity as it requires access to the execution properties to get the ambient RuntimeTransactionHandle. In the Execute method, it obtains the RuntimeTransactionHandle and checks whether it is null, which indicates that the activity was used without an ambient run-time transaction. It then obtains the transaction, again checking whether null is present. It is possible to have an ambient RuntimeTransactionHandle without ever initializing a run-time transaction. Finally it aborts the transaction by calling Rollback and specifying either a user-provided exception or a generic exception that states that the activity rolled back the transaction.

The demonstration workflow consists of a TransactionScope whose body prints the transaction status before and after the RollbackActivity executes. Note that even though the transaction has been rolled back, the TransactionScope executes to completion and does not abort the workflow until the body completes. The workflow is aborted because the AbortInstanceOnTransactionFailure property defaults to true.

To use this sample

  1. Load the TransactionRollback.sln solution in Visual Studio 2010.

  2. Press CTRL+SHIFT+B to build the solution.

  3. Press CTRL+F5 to run the application.

Ee656553.Important(en-us,VS.100).gif Note:
The samples may already be installed on your computer. Check for the following (default) directory before continuing.

<InstallDrive>:\WF_WCF_Samples

If this directory does not exist, go to Windows Communication Foundation (WCF) and Windows Workflow Foundation (WF) Samples for .NET Framework 4 to download all Windows Communication Foundation (WCF) and WF samples. This sample is located in the following directory.

<InstallDrive>:\WF_WCF_Samples\WF\Scenario\Transactions\TransactionRollback

See Also

Concepts

Workflow Transactions