15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

system.Transactions ❘ 623<br />

Creation Time: 21:41:25<br />

Status: Active<br />

Local ID: f1e736ae-84ab-4540-b71e-3de272ffc476:2<br />

Distributed ID: 00000000-0000-0000-0000-000000000000<br />

TX completed<br />

Creation Time: 21:41:25<br />

Status: Committed<br />

Local ID: f1e736ae-84ab-4540-b71e-3de272ffc476:2<br />

Distributed ID: 00000000-0000-0000-0000-000000000000<br />

To use the same ambient transaction in another thread, you need the help of dependent transactions. Now,<br />

the sample is changed to pass a dependent transaction to the new thread. The dependent transaction is<br />

created from the ambient transaction by calling the DependentClone() method on the ambient transaction.<br />

With this method, the setting DependentCloneOption.BlockCommitUntilComplete is set so that the<br />

calling thread waits until the new thread is completed before committing the transaction:<br />

class Program<br />

{<br />

static void Main()<br />

{<br />

try<br />

{<br />

using (var scope = new TransactionScope())<br />

{<br />

Transaction.Current.TransactionCompleted +=<br />

TransactionCompleted;<br />

Utilities.DisplayTransactionInformation("Main thread TX",<br />

Transaction.Current.TransactionInformation);<br />

new Thread(ThreadMethod).Start(<br />

Transaction.Current.DependentClone(<br />

DependentCloneOption.BlockCommitUntilComplete));<br />

scope.Complete();<br />

}<br />

}<br />

catch (TransactionAbortedException ex)<br />

{<br />

Console.WriteLine("Main—Transaction was aborted, {0}",<br />

ex.Message);<br />

}<br />

}<br />

In the method of the thread, the dependent transaction that is passed is assigned to the ambient transaction<br />

by using the set accessor of the Transaction.Current property. Now the transaction scope is using<br />

the same transaction by using the dependent transaction. When you are finished using the dependent<br />

transaction, you need to invoke the Complete() method of the DependentTransaction object:<br />

static void ThreadMethod(object dependentTx)<br />

{<br />

DependentTransaction dTx = dependentTx as DependentTransaction;<br />

try<br />

{<br />

Transaction.Current = dTx;<br />

using (var scope = new TransactionScope())<br />

{<br />

Transaction.Current.TransactionCompleted +=<br />

TransactionCompleted;<br />

Utilities.DisplayTransactionInformation("Thread TX",<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!