C# 如何查找交易状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9934331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 11:17:13  来源:igfitidea点击:

How to find the Transaction Status

c#asp.nettransactionstransactionscope

提问by Muzaffar Ali Rana

I am using 'TransactionScope', and I need to just do some DML within the C# Code, which I have successfully.

I need to find out that what is the status of the Transaction, that is has it completed successfully or not ?

Because on the basis of the Transaction Status, if the transaction is complete then I need to perform a redirect to another page, otherwise if the transaction is not completed successfully then I need to show the error on the page.

I want to redirect after the following:-
scope.Complete();
scope.Dispose();

我正在使用“TransactionScope”,我只需要在 C# 代码中做一些 DML,我已经成功了。

我需要找出事务的状态什么,即它是否成功完成?

因为在交易状态的基础上,如果交易完成,那么我需要执行重定向到另一个页面,否则如果交易没有成功完成,那么我需要在页面上显示错误。

我想在以下之后重定向:-
scope.Complete();
范围.处置();

Please help me in this regards.

请在这方面帮助我。

采纳答案by C???

If you visit the MSDN pagefor TransactionScope, you would find this well-documented example:

如果你访问MSDN页面TransactionScope,你会发现这充分证明例如:

try
{
    // Create the TransactionScope to execute the commands, guaranteeing
    // that both commands can commit or roll back as a single unit of work.
    using (TransactionScope scope = new TransactionScope())
    {
        using (SqlConnection connection1 = new SqlConnection(connectString1))
        {
            // Opening the connection automatically enlists it in the 
            // TransactionScope as a lightweight transaction.
            connection1.Open();

            // Create the SqlCommand object and execute the first command.
            SqlCommand command1 = new SqlCommand(commandText1, connection1);
            returnValue = command1.ExecuteNonQuery();
            writer.WriteLine("Rows to be affected by command1: {0}", returnValue);

            // If you get here, this means that command1 succeeded. By nesting
            // the using block for connection2 inside that of connection1, you
            // conserve server and network resources as connection2 is opened
            // only when there is a chance that the transaction can commit.   
            using (SqlConnection connection2 = new SqlConnection(connectString2))
            {
                // The transaction is escalated to a full distributed
                // transaction when connection2 is opened.
                connection2.Open();

                // Execute the second command in the second database.
                returnValue = 0;
                SqlCommand command2 = new SqlCommand(commandText2, connection2);
                returnValue = command2.ExecuteNonQuery();
                writer.WriteLine("Rows to be affected by command2: {0}", returnValue);
            }
        }

        // The Complete method commits the transaction. If an exception has been thrown,
        // Complete is not  called and the transaction is rolled back.
        scope.Complete();

    }

}
catch (TransactionAbortedException ex)
{
    writer.WriteLine("TransactionAbortedException Message: {0}", ex.Message);
}
catch (ApplicationException ex)
{
    writer.WriteLine("ApplicationException Message: {0}", ex.Message);
}

The comment that contains the most value is this one:

包含最多价值的评论是这个:

The Complete method commits the transaction. If an exception has been thrown, Complete is not called and the transaction is rolled back.

Complete 方法提交事务。如果抛出异常,则不会调用 Complete 并回滚事务。

So, if no exceptions are thrown, you can continue on. Put your redirect after scope.Complete(). If an exception is thrown, the transaction failed and has automatically been rolled back. You could double-check the transaction status (as others have posted) after the call to Complete()and before you redirect, via Transaction.Current.TransactionInformation.Status:

所以,如果没有抛出异常,你可以继续。将您的重定向放在scope.Complete(). 如果抛出异常,则事务失败并已自动回滚。您可以在调用之后Complete()和重定向之前通过Transaction.Current.TransactionInformation.Status以下方式仔细检查交易状态(如其他人发布的那样):

if (Transaction.Current.TransactionInformation.Status == TransactionStatus.Committed) 
{
    // do redirect
}

回答by JotaBe

Use Transaction.Current.TransactionInformation.Status

Transaction.Current.TransactionInformation.Status

Transaction.Current Property

交易.当前属性

Transaction.TransactionInformation Property

Transaction.TransactionInformation 属性

回答by Drew Marsh

How about:

怎么样:

TransactionStatus status = Transaction.Current.TransactionInformation.Status;

回答by Paul Zahra

The best method I've found for capturing this most efficiently / correctly is as follows:

我找到的最有效/正确地捕获此信息的最佳方法如下:

Inside the transactionscope using statement, and before the call to scope/Complete().

在事务范围 using 语句中,在调用范围/Complete() 之前。

//Register for the transaction completed event for the current transaction
Transaction.Current.TransactionCompleted += new TransactionCompletedEventHandler(Current_TransactionCompleted);

Then create the event handler function as follows:

然后创建事件处理函数如下:

/// <summary>
/// Handles the TransactionCompleted event of the Current control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Transactions.TransactionEventArgs"/> instance containing the event data.</param>
static void Current_TransactionCompleted(object sender, TransactionEventArgs e)
{
    if (e.Transaction.TransactionInformation.Status == TransactionStatus.Committed)
    {
        /// Yay it's committed code goes here!
    }
}

To quote MSDN

引用MSDN

"You can register for this event instead of using a volatile enlistment to get outcome information for transactions. The parameter passed to the TransactionCompletedEventHandler delegate is a Transaction instance. You can then query the TransactionInformation property of the specific instance to get an instance of TransactionInformation, whose Status property contains the status of a transaction with either the Committed or Aborted value."

“您可以注册此事件而不是使用易失性登记来获取交易的结果信息。传递给 TransactionCompletedEventHandler 委托的参数是一个 Transaction 实例。然后您可以查询特定实例的 TransactionInformation 属性以获取 TransactionInformation 的实例,其 Status 属性包含具有 Committed 或 Aborted 值的事务的状态。”