C# Transaction 事务处理

class

 1 //student
 2  [Serializable]
 3     public class Student
 4     {
 5         public string FirstName { get; set; }
 6         public string LastName { get; set; }
 7         public string Company { get; set; }
 8         public int Id { get; set; }
 9 
10         public override string ToString()
11         {
12             return String.Format("{0} {1}", FirstName, LastName);
13         }
14     }
15 
16 //student 处理类
17  public async Task AddStudentAsync(Student student, Transaction tx)
18         {
19             SqlConnection connection = new SqlConnection(Settings.Default.CourseConnection);
20             await connection.OpenAsync();
21             try
22             {
23                 if (tx != null)
24                     connection.EnlistTransaction(tx);
25                 SqlCommand command = connection.CreateCommand();
26                 command.CommandText = "INSERT INTO Students (FirstName, LastName, Company) " +
27                "VALUES (@FirstName, @LastName, @Company)";
28                 command.Parameters.AddWithValue("@FirstName", student.FirstName);
29                 command.Parameters.AddWithValue("@LastName", student.LastName);
30                 command.Parameters.AddWithValue("@Company", student.Company);
31                 await command.ExecuteNonQueryAsync();
32             }
33             catch (Exception ex)
34             {
35                 Trace.WriteLine("AddStudentAsync(Student student, Transaction tx) Error :" + ex.Message);
36                 throw;
37             }
38             finally
39             { connection.Close(); }
40         }
41 
42 //操作类
43   public static class Utilities
44     {
45        public static bool AbortTx()
46        {
47            Console.Write("Abort the Transaction (y/n)?");
48            return Console.ReadLine().ToLower().Equals("y");
49        }
50        public static void DisplayTransactionInformation(string title, TransactionInformation ti)
51        {
52            Contract.Requires<ArgumentNullException>(ti != null);
53 
54            Console.WriteLine(title);
55            Console.WriteLine("Creation Time: {0:T}", ti.CreationTime);
56            Console.WriteLine("Status: {0}", ti.Status);
57            Console.WriteLine("Local ID: {0}", ti.LocalIdentifier);
58            Console.WriteLine("Distributed ID: {0}", ti.DistributedIdentifier);
59            Console.WriteLine();
60        }
61     }
View Code

执行类

 1   static void Main(string[] args)
 2         {
 3            Task t= CommittableTransactionAsync();
 4            t.Wait();
 5         }
 6         static async Task CommittableTransactionAsync()
 7         {
 8             var tx = new CommittableTransaction();
 9             Utilities.DisplayTransactionInformation("TX created", tx.TransactionInformation);
10 
11             try
12             {
13                 var s1 = new Student() { FirstName = "Stephanie", LastName = "Nage1", Company = "China" };
14                 var db = new StudentData();
15                 await db.AddStudentAsync(s1,tx);
16 
17                 var s2 = new Student() { FirstName = "Stephanie2", LastName = "Nage2", Company = "China" };
18                 await db.AddStudentAsync(s2, tx);
19 
20                 Utilities.DisplayTransactionInformation("2nd connection enlisted ", tx.TransactionInformation);
21 
22                 if(Utilities.AbortTx())
23                 {
24                     throw new ApplicationException("transaction abort");
25                 }
26                 tx.Commit();
27             }
28             catch (Exception ex)
29             {
30                 Console.WriteLine(ex.Message);
31                 Console.WriteLine();
32                 tx.Rollback();
33             }
34             Utilities.DisplayTransactionInformation("TX completed", tx.TransactionInformation);
35         }
原文地址:https://www.cnblogs.com/farmer-y/p/6108748.html