string constr = ConfigurationManager.ConnectionStrings[“myCon”].ConnectionString;
            string constr2 = ConfigurationManager.ConnectionStrings[“myCon2”].ConnectionString;
            string sql = “insert into [Tuser](username,pwd,age) values(\’CommittableTransaction事务\’,\’bbb\’,10)”;
            string sq2 = “insert into [Tuser](username,pwd,age) values(\’CommittableTransaction事务\’,\’bbb\’,\’sssssss\’)”;

 

  #region CommittableTransaction 分布式
            using(SqlConnection con=new SqlConnection(constr),con2=new SqlConnection(constr2))
            {
                con.Open();
                con2.Open();
                CommittableTransaction ct = new CommittableTransaction();//CommittableTransaction要在连接打开后创建
                //由此可看出事务的性能并不好。
                con.EnlistTransaction(ct);//在CommittableTransaction登记分布式事务
                con2.EnlistTransaction(ct);
                try
                {
                    using (SqlCommand cmd = new SqlCommand(sql, con))
                    {

                        int a = cmd.ExecuteNonQuery();
                        Console.WriteLine(a);

                    }
                    using (SqlCommand cmd = new SqlCommand(sq2, con2))
                    {

                        int b = cmd.ExecuteNonQuery();
                        Console.WriteLine(b);

                    }
                    ct.Commit();//提交事务
                }
                catch (Exception ess)
                {
                    Console.WriteLine(ess.Message);
                    ct.Rollback();//回滚事务
                                      
                }
               //因为了连接在其他地方使用。必须清除分布事务。
                con.EnlistTransaction(null);
                con2.EnlistTransaction(null);
            }

            #endregion

 

虽然实现了分布式的事务。但感觉性能真的太差。故在能不用分布式事务。最好不要用。特别是多事务并发时候。

版权声明:本文为zhbsh原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/zhbsh/archive/2011/05/14/2046054.html