15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

system.Transactions ❘ 617<br />

tx.Complete();<br />

}<br />

Utilities.DisplayTransactionInformation("Dependent TX Complete",<br />

tx.TransactionInformation);<br />

code snippet TransactionSamples/Program.cs<br />

With the DependentTransaction() method, fi rst a root transaction is created by instantiating<br />

the class CommittableTransaction , <strong>and</strong> the transaction information is shown. Next, the method<br />

tx.DependentClone() creates a dependent transaction. This dependent transaction is passed to the<br />

method TxThread() that is defi ned as the entry point of a new thread.<br />

The method DependentClone() requires an argument of type DependentCloneOption , which<br />

is an enumeration with the values BlockCommitUntilComplete <strong>and</strong> RollbackIfNotComplete .<br />

This option is important if the root transaction completes before the dependent transaction. Setting the<br />

option to RollbackIfNotComplete , the transaction aborts if the dependent transaction didn ’ t invoke<br />

the Complete() method before the Commit() method of the root transaction. Setting the option to<br />

BlockCommitUntilComplete , the method Commit() waits until the outcome is defi ned by all dependent<br />

transactions.<br />

Next, the Commit() method of the CommittableTransaction class is invoked if the user does not abort the<br />

transaction.<br />

Chapter 20, “Threads, Tasks, <strong>and</strong> Synchronization,” covers threading.<br />

static void DependentTransaction()<br />

{<br />

var tx = new CommittableTransaction();<br />

Utilities.DisplayTransactionInformation("Root TX created",<br />

tx.TransactionInformation);<br />

try<br />

{<br />

new Thread(TxThread).Start(tx.DependentClone(<br />

DependentCloneOption.BlockCommitUntilComplete));<br />

if (Utilities.AbortTx())<br />

{<br />

throw new ApplicationException("transaction abort");<br />

}<br />

tx.Commit();<br />

}<br />

catch (Exception ex)<br />

{<br />

Console.WriteLine(ex.Message);<br />

tx.Rollback();<br />

}<br />

}<br />

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

tx.TransactionInformation);<br />

code snippet TransactionSamples/Program.cs<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!