C# Transaction 事务处理 -依赖事务

 在DependentTransaction()方法中,实例化CommittableTransaction类,创建一个根事务,显示事务的信息。接着, tx.DependentClone()方法创建一个依赖的事务。把这个依赖事务传递给TxTask()方法,它定义为新任务的入口。

 1 static void DependentTransaction()
 2         {
 3             var tx = new CommittableTransaction();
 4             Utilities.DisplayTransactionInformation("Root TX created",
 5                   tx.TransactionInformation);
 6 
 7             try
 8             {
 9                 Task.Factory.StartNew(TxTask, tx.DependentClone(DependentCloneOption.BlockCommitUntilComplete));
10 
11                 if (Utilities.AbortTx())
12                 {
13                     throw new ApplicationException("transaction abort");
14                 }
15 
16                 tx.Commit();
17             }
18             catch (Exception ex)
19             {
20                 Console.WriteLine(ex.Message);
21                 tx.Rollback();
22             }
23 
24             Utilities.DisplayTransactionInformation("TX finished",
25                   tx.TransactionInformation);
26 
27         }
28 
29         static void TxTask(object obj)
30         {
31             var tx = obj as DependentTransaction;
32             Utilities.DisplayTransactionInformation("Dependent Transaction",
33                   tx.TransactionInformation);
34 
35             Thread.Sleep(3000);
36 
37             tx.Complete();
38 
39             Utilities.DisplayTransactionInformation("Dependent TX Complete",
40                   tx.TransactionInformation);
41         }
42 
43    public static class Utilities
44     {
45        public static void DisplayTransactionInformation(string title, TransactionInformation ti)
46        {
47            Contract.Requires<ArgumentNullException>(ti != null);
48 
49            Console.WriteLine(title);
50            Console.WriteLine("Creation Time: {0:T}", ti.CreationTime);
51            Console.WriteLine("Status: {0}", ti.Status);
52            Console.WriteLine("Local ID: {0}", ti.LocalIdentifier);
53            Console.WriteLine("Distributed ID: {0}", ti.DistributedIdentifier);
54            Console.WriteLine();
55        }
56     }

 

posted @ 2016-11-28 15:16  指间的徘徊  阅读(618)  评论(0编辑  收藏  举报