1public void Insert(string UserName,ArrayList alRoles)
2{
3using (TransactionScope _ts = new TransactionScope())
4{
5 //插入用户
6 new user().Insert(UserName);
7
8 // 插入角色
9 new Role().Insert(UserName,alRoles);
10
11 _ts.Complete();
12}
13}
2{
3using (TransactionScope _ts = new TransactionScope())
4{
5 //插入用户
6 new user().Insert(UserName);
7
8 // 插入角色
9 new Role().Insert(UserName,alRoles);
10
11 _ts.Complete();
12}
13}
异步提交事务的代码也很简单:
1 public void Work()
2 {
3 Transaction _old = Transaction.Current;
4 CommittableTransaction _newCommit = new CommittableTransaction();
5 Transaction.Current = _newCommit;
6
7 try
8 {
9 _newCommit.BeginCommit(OnCommit, null);
10 }
11 finally
12 {
13 Transaction.Current = _old;
14 }
15 }
16 void OnCommit(IAsyncResult asy)
17 {
18 CommittableTransaction _commit;
19 _commit = asy as CommittableTransaction;
20
21 try
22 {
23 using (_commit)
24 {
25 SqlConnection _cnn = new SqlConnection("");
26 SqlCommand _cmd = new SqlCommand();
27
28
29 _cnn.Open();
30
31 _cnn.EnlistTransaction(_commit); // 利用事务
32
33 _cmd.Connection = _cnn;
34
35 _cmd.CommandText = ".";
36 _cmd.ExecuteNonQuery();
37
38 _cmd.CommandText = "";
39 _cmd.ExecuteNonQuery();
40
41 _commit.EndCommit(asy);
42
43 _cnn.Close();
44 }
45 }
46 catch (Exception e)
47 {
48
49 }
50 }
2 {
3 Transaction _old = Transaction.Current;
4 CommittableTransaction _newCommit = new CommittableTransaction();
5 Transaction.Current = _newCommit;
6
7 try
8 {
9 _newCommit.BeginCommit(OnCommit, null);
10 }
11 finally
12 {
13 Transaction.Current = _old;
14 }
15 }
16 void OnCommit(IAsyncResult asy)
17 {
18 CommittableTransaction _commit;
19 _commit = asy as CommittableTransaction;
20
21 try
22 {
23 using (_commit)
24 {
25 SqlConnection _cnn = new SqlConnection("");
26 SqlCommand _cmd = new SqlCommand();
27
28
29 _cnn.Open();
30
31 _cnn.EnlistTransaction(_commit); // 利用事务
32
33 _cmd.Connection = _cnn;
34
35 _cmd.CommandText = ".";
36 _cmd.ExecuteNonQuery();
37
38 _cmd.CommandText = "";
39 _cmd.ExecuteNonQuery();
40
41 _commit.EndCommit(asy);
42
43 _cnn.Close();
44 }
45 }
46 catch (Exception e)
47 {
48
49 }
50 }
上面我们用TransactionScope和CommittableTransaction。
TransactionScope是隐示的,是由系统自动管理的,所以它没有什么RollBack方法。
CommittableTransaction是显示的,它有commit和RollBack方法。
------------------------------------------
以上都是个人的看法和体会,如有不妥处,还请大家多多指点,谢谢!
本文转自BearRui(AK-47)博客园博客,原文链接:http://www.cnblogs.com/BearsTaR/archive/2006/04/17/Transactions.html ,如需转载请自行联系原作者