共用方式為


Using Compensation in Workflows

Compensation in Windows Workflow Foundation is the mechanism by which previously completed work can be undone or compensated (following the logic defined by the application) when a subsequent failure occurs. Transactions allow you to combine multiple operations into a single unit of work. Using a transaction allows your application to abort (roll back) all changes executed from within the transaction if any errors occur during any part of the transaction process. However, using transactions may not be appropriate if the work is long running. For example, a travel planning application is implemented as a workflow. The steps of the workflow consist of booking a flight, waiting for manager approval, and then paying for the flight. This process could take many days and it is not practical for the steps of booking and paying for the flight to participate in the same transaction. In this scenario, compensation could be used to undo the booking step of the workflow if there is a failure later in the processing.

To use compensation, activities that execute logic that should be undone or compensated if the workflow fails to complete can be placed in a CompensatableSequenceActivity activity, and activities that are used to undo or compensate the work can be placed in the compensation handler of the CompensatableSequenceActivity activity. When the CompensatableSequenceActivity activity executes, its child activities are executed. If compensation is performed, the activities in the compensation handler are executed.

Note

Compensation can also apply for short running work. If this short running work is transactional, you can use a CompensatableTransactionScopeActivity activity. The child activities of the CompensatableTransactionScopeActivity activity execute in the scope of a transaction in the same fashion as a TransactionScopeActivity activity, but can be compensated in the same fashion as a CompensatableSequenceActivity activity.

Compensation of the activities in a workflow can be invoked in one of two ways:

  • Implicit is the default mechanism. When an exception passes the root of the activity that contains the completed CompensatableSequenceActivity activity, compensation is invoked for that activity.

  • Explicit, when the CompensateActivity activity is used. For more information, see Using the CompensateActivity Activity.

See Also

Concepts

Using the CompensateActivity Activity
Using the CompensatableSequenceActivity Activity
Using the CompensatableTransactionScopeActivity Activity
Using Transactions in Workflows

Other Resources

Developing Workflows
Compensation Sample