【问题标题】:Determining if a TransactionScope is committed or not确定 TransactionScope 是否已提交
【发布时间】:2012-01-09 16:02:38
【问题描述】:

使用 .net 2 和 ADO.NET。

有没有办法确定事务是否已提交?原因是我坚持使用无法更改的遗留框架,并且可能存在也可能不存在环境事务。有时环境事务已经提交,导致下一次数据库调用抛出异常,我需要知道它是否是。

任何指针都会很棒!

谢谢

约翰

【问题讨论】:

  • 发布一些当前代码库的示例会有所帮助。

标签: .net sql-server ado.net transactionscope


【解决方案1】:

检查Transaction.Current.TransactionInformation.Status。如果不是TransactionStatus.Active,则不应使用当前事务。

不用说,在获取其状态之前,您应该检查 Transaction.Current 中的 null

【讨论】:

    【解决方案2】:

    我发现的最有效/正确捕获这一点的最佳方法如下:

    在事务作用域的 using 语句中,在调用 scope/Complete() 之前。

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

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

    /// <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!
        }
    }
    

    引用MSDN

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

    【讨论】:

      猜你喜欢
      • 2014-02-15
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多