使用.Net2.0的事务

在1.1框架时困扰我很久的事件调用处理终于在2.0的时候有了很好的解决方案.
1.1的时候因为企业事务要涉及COM+,而我对COM+又不懂,所以一直没有偿试它,而是采用ADO.Net的本地级事务.ADO.Net的事件有两个弱点:(1)不能实现分布式事务;(2)不能够很好的处理事务嵌套.
在2.0框架下,可以使用System.Transactions这个命名空间下的一些类,其中System.Transactions.TransactionScope,实现了隐式的事务处理方式,可以判断事务的类型来使用本地级事务或者是分布式事务.我的测试代码如下:

            try
            
{
                
using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
                
{
                    
using (System.Data.SqlClient.SqlConnection sql1 = new System.Data.SqlClient.SqlConnection(@"Data Source=LYSERVER\LYSERVER;Initial Catalog=pubs;Persist Security Info=True;User ID=sa"))
                    
{
                        sql1.Open();
                        System.Data.SqlClient.SqlCommand cmd 
= new System.Data.SqlClient.SqlCommand();
                        cmd.Connection 
= sql1;
                        cmd.CommandText 
= "INSERT INTO stores(stor_id,stor_name,stor_address,city,state,zip) values('8888','测试分布式事务','沈阳市三好街','沈阳','LY','111')";
                        cmd.ExecuteNonQuery();
                        sql1.Close();
                    }

                    
if (MessageBox.Show("您要中断对本地数据库的访问吗?""", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    
{
                        
throw new Exception("用户中断,自动回滚全部事务!");
                    }

                    
using (System.Data.SqlClient.SqlConnection sql1 = new System.Data.SqlClient.SqlConnection(@"Data Source=wu;Initial Catalog=pubs;Integrated Security=True"))
                    
{
                        sql1.Open();
                        System.Data.SqlClient.SqlCommand cmd 
= new System.Data.SqlClient.SqlCommand();
                        cmd.Connection 
= sql1;
                        cmd.CommandText 
= "INSERT INTO stores(stor_id,stor_name,stor_address,city,state,zip) values('8888','测试分布式事务','沈阳市三好街','沈阳','LY','111')";
                        cmd.ExecuteNonQuery();
                        sql1.Close();
                    }

                    scope.Complete();
                    MessageBox.Show(
"commited");
                }

            }

            
catch (Exception ex)
            
{
                MessageBox.Show(ex.Message);
            }
注意:在使用System.Transactions时,VS2005并没有引用其相应的Dll,需要手动的引用System.Transaction.dll.
posted @ 2007-03-14 14:58  吴东雷  阅读(400)  评论(0编辑  收藏  举报