How Do I...Use transactions across threads?
If you want to start asynchronous threads and have them participate in a transaction, use the DepedentTransaction object. DependentTransction objects can be obtained by called the DependentClone method on a Transaction object. A thread can use a DependentTransaction in a TransactionScope or use the transaction explicitly to perform transacted work. When the thread is done with the transaction, it simply calls the complete method on the DependentTransaction. In case of failure, the rollback method can be called.
The code starting the thread has two options when using a DependentClone:
- BlockCommitUntilComplete: The transaction will not commit until the Complete method is called on the DependentTransaction or the transaction times out, even if the commit method is called on the transaction. Choose this option if you want to wait for the thread to finish before committing the transaction but don't want to manually track when the thread is complete.
- RollbackIfNotComplete: The transaction will rollback if the Commit method is called on the transaction before the Complete method is called on the DepedentTransaction. Choose this option if you expect the thread to be done when you call commit. The transaction will be aborted if the thread is not done with it's transacted work before Commit is called.
1. Create a DependentClone of the transaction you want to do work on in another thread
DependentTransaction MyDependentTx = MyTx.DependentClone(DependentCloneOption.BlockCommitUntilComplete));
C#
2. In the thread, pass the dependent transaction to a TransactionScope object, do work within that TransactionScope and call complete on the TransactionScope. Once the thread is finished with all work on the transaction, call complete on the DependentTransaction object.
private static void WorkerThread(object transaction)
{
DependentTransaction dTx = (DependentTransaction)transaction;
using (TransactionScope ts = new TransactionScope(dTx))
{
//Perform transactional work here.
//Call complete on the transaction scope
ts.Complete();
}
//Call complete on the dependent transaction
dTx.Complete();
}
C#
Here is a full example:
[This sample can be found at M:\web\users\Sites\AspnetQuickStart\v2.0\QuickStart\howto\samples\Transactions\DependentTx
To build this sample, open the SDK command prompt and navigate to the above path. Build the sample using the build tool msbuild
passing the solution file as the first parameter: msbuild mySample.sln. The compiled executable will be found in the sub directory \bin
directory.]
Microsoft .NET Framework SDK QuickStart Tutorials Version 2.0
Copyright � 2005 Microsoft Corporation. All rights reserved.
|