假设要Insert1个用户和该用户对应角色,而这2个Insert方法已经封装到2个dll中了,现在要在这个2个方法中实现事务,代码很简单,如下(需先添加对System.Transactions程序集的引用)
上面我们用TransactionScope和CommittableTransaction。
TransactionScope是隐示的,是由系统自动管理的,所以它没有什么RollBack方法。
CommittableTransaction是显示的,它有commit和RollBack方法。
------------------------------------------
以上都是个人的看法和体会,如有不妥处,还请大家多多指点,谢谢!
1
public void Insert(string UserName,ArrayList alRoles)
2
{
3
using (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

3

4

5

6

7

8

9

10

11

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

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25


26

27

28

29

30

31

32

33

34

35


36

37

38


39

40

41

42

43

44

45

46

47

48

49

50

上面我们用TransactionScope和CommittableTransaction。
TransactionScope是隐示的,是由系统自动管理的,所以它没有什么RollBack方法。
CommittableTransaction是显示的,它有commit和RollBack方法。
------------------------------------------
以上都是个人的看法和体会,如有不妥处,还请大家多多指点,谢谢!