BearRui(AK-47)
花开有时,错过了一日便错过了一季,就象人生错过了相遇,就不再找寻到美丽的相聚
随笔- 39  文章- 2  评论- 1291 
博客园  首页  新随笔  联系  管理  订阅 订阅
在组件之间实现事务和异步提交事务(NET2.0)
假设要Insert1个用户和该用户对应角色,而这2个Insert方法已经封装到2个dll中了,现在要在这个2个方法中实现事务,代码很简单,如下(需先添加对System.Transactions程序集的引用)

 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}

异步提交事务的代码也很简单:

 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        }

上面我们用TransactionScope和CommittableTransaction。
TransactionScope是隐示的,是由系统自动管理的,所以它没有什么RollBack方法。
CommittableTransaction是显示的,它有commit和RollBack方法。
------------------------------------------
以上都是个人的看法和体会,如有不妥处,还请大家多多指点,谢谢!
posted on 2006-04-17 14:15 BearRui(AK-47) 阅读(1377) 评论(6) 编辑 收藏
刷新评论刷新页面返回顶部
程序员问答社区,解决您的IT难题
博客园首页博问新闻闪存程序员招聘知识库
Copyright ©2012 BearRui(AK-47)