Execute a Workflow in an Imperative TransactionScope

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

This sample shows how to execute a workflow using WorkflowInvoker under a Transaction from imperative C# code.

Sample Details

In imperative C# code, the TransactionScope is used to encapsulate a set of work that executes under the same transaction. The TransactionScope works by creating an ambient transaction and initializing the Current property, which can then be accessed by any work being executed on that thread.

To get equivalent behavior in workflow, the runtime has to do the extra work of initializing Current before executing each activity because a workflow does not maintain thread affinity between activities. With this runtime support, the resulting behavior is that when executing a workflow with WorkflowInvoker inside a TransactionScope, all activities are guaranteed to run under the context of the ambient transaction created by the TransactionScope.

A workflow can have only a single ambient transaction for each workflow instance; nested transactions are not available. Even if the workflow contains a TransactionScope activity, this does not create a new inner transaction. Instead, this reuses the ambient transaction that was created outside the workflow.

The sample begins a new TransactionScope, prints the transaction ID and begins a workflow using WorkflowInvoker. The workflow prints the transaction ID again, showing that it is the same transaction, then runs a TransactionScope, then completes. The Invoke call on WorkflowInvoker is synchronous so the original thread blocks until the workflow completes. Once the workflow is complete, the transaction is completed and resources disposed.

To use this sample

  1. Using Visual Studio 2010, open the ImperativeTransactionSample.sln solution file.

  2. To build the solution, press CTRL+SHIFT+B.

  3. To run the solution, press F5.

Dd759027.Important(en-us,VS.100).gif Note:
The samples may already be installed on your machine. 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\ImperativeTransaction