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 ❘ 621<br />

A GUID is a globally unique identifi er consisting of a 128-bit unique value.<br />

Ambient TX created<br />

Creation Time: 11:01:09 PM<br />

Status: Active<br />

Local ID: 54ac1276-5c2d-4159-84ab-36b0217c9c84:1<br />

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

Inner Transaction Scope<br />

Creation Time: 11:01:09 PM<br />

Status: Active<br />

Local ID: 54ac1276-5c2d-4159-84ab-36b0217c9c84:2<br />

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

TX completed<br />

Creation Time: 11:01:09 PM<br />

Status: Committed<br />

Local ID: 54ac1276-5c2d-4159-84ab-36b0217c9c84:2<br />

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

TX completed<br />

Creation Time: 11:01:09 PM<br />

Status: Committed<br />

Local ID: 54ac1276-5c2d-4159-84ab-36b0217c9c84:1<br />

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

If you change the inner scope to the setting TransactionScopeOption.Required , you will fi nd that both<br />

scopes are using the same transaction, <strong>and</strong> both scopes infl uence the outcome of the transaction.<br />

Multithreading with ambient Transactions<br />

If multiple threads should use the same ambient transaction, you need to do some extra work. An ambient<br />

transaction is bound to a thread, so if a new thread is created, it does not have the ambient transaction from<br />

the starter thread.<br />

This behavior is demonstrated in the next example. In the Main() method, a TransactionScope is created.<br />

Within this transaction scope, a new thread is started. The main method of the new thread ThreadMethod()<br />

creates a new transaction scope. With the creation of the scope, no parameters are passed, <strong>and</strong> therefore,<br />

the default option TransactionScopeOption.Required gets into play. If an ambient transaction exists, the<br />

existing transaction is used. If there is no ambient transaction, a new transaction is created:<br />

using System;<br />

using System.Threading;<br />

using System.Transactions;<br />

namespace Wrox.ProCSharp.Transactions<br />

{<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 />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!