交易范围和多个区域

时间:2014-07-02 13:37:47

标签: c# asp.net sql-server transactions transactionscope

交易范围是否跨多个地区运作?如果我有2个进程,一个打开连接和事务,执行插入命令然后在事务关闭之前调用另一个进程,如果事务2失败,原始事务是否会考虑?以下是示例代码。

区域1:

public static void process1()
{
    using (SqlConnection conn = new SqlConnection(Connections.conn()))
    {
        //Open the connection
        conn.Open();

        try
        {
            //Create A new Sql transaction.
            using (var trans = new System.Transactions.TransactionScope())
            {
               using (SqlCommand insert = new SqlCommand
               {
                CommandType = CommandType.Text,
                CommandText = sql,
                Connection = conn,
                CommandTimeout = 300
                })
                {                            
                    insert.ExecuteNonQuery();
                }
            process2()
            trans.complete();
            }
         }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
    }
}

区域2

public static void process2()
{
    using (SqlConnection conn = new SqlConnection(Connections.conn()))
    {
        //Open the connection
        conn.Open();

        try
        {
            //Create A new Sql transaction.
            using (var trans2 = new System.Transactions.TransactionScope())
            {
               using (SqlCommand insert = new SqlCommand
               {
                CommandType = CommandType.Text,
                CommandText = sql,
                Connection = conn,
                CommandTimeout = 300
                })
                {                            
                    insert.ExecuteNonQuery();
                }
            trans2.complete();
            }
         }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
    }
}

在我的申请过程中,2取决于过程1的成功。如果过程1成功而过程2不成功则过程1的结果无效。

据我所知,当commans在同一个事务块中执行时,如果有的话,它们都会失败,但是当我编写我的应用程序来执行它时,我想知道在这种情况下是否应用了相同的区域。我宁愿不必一起重新编码两个不同的过程。

提前致谢,

1 个答案:

答案 0 :(得分:1)

如果这只是单个C#文件中的两个代码块,那么为了确保两个进程都发生或两者都没有发生,您也希望将对这些函数的调用包装在事务范围内。像这样:

using (var tx = new TransactionScope()) {
     process1();
     process2();
     tx.Complete();
}

这样,如果process1或process2失败,两者都将被回滚。