【问题标题】:Get the transaction title from an SqlTransaction object从 SqlTransaction 对象中获取事务标题
【发布时间】:2026-01-21 01:20:04
【问题描述】:

使用BeginTransaction("MyTransactionName")创建SqlTransaction对象时,有没有办法从返回的事务对象中获取事务的名称?

想法是当我的事务失败时,我想记录事务的名称,因为系统是多线程的,并且会发生一些需要处理的死锁。

我的示例代码中的logger 对象是我们自己的组件,这是一个非常简单的示例,因为很多代码无法在此处发布。

 using (SqlConnection myConnection = new SqlConnection(SQLConnectString)) {
     myConnection.Open();
     SqlTransaction transaction = myConnection.BeginTransaction("UpdateTransaction");

     //The update methods are omitted here for brevity

     try {
         logger.Log("Attempt commit ");
         transaction.Commit();
     } catch (Exception ex) {
         logger.Error("Commit failed - " + ex.Message, ex.StackTrace);
         //At this point, I want to write the name of the failed
         //transaction into the log.
     }
}

任何帮助将不胜感激。

【问题讨论】:

    标签: c# sql-server transactions


    【解决方案1】:

    尝试添加另一个catch块

    catch (SqlException ex)
        {
            for (int i = 0; i < ex.Errors.Count; i++)
            {
                errorMessages.Append("Index #" + i + "\n" +
                    "Message: " + ex.Errors[i].Message + "\n" +
                    "LineNumber: " + ex.Errors[i].LineNumber + "\n" +
                    "Source: " + ex.Errors[i].Source + "\n" +
                    "Procedure: " + ex.Errors[i].Procedure + "\n");
            }
           logger.Error(errorMessages.ToString());
        }
    

    【讨论】:

      【解决方案2】:

      我确定您正在寻找更优雅的东西,但有时简单的修复就可以解决问题。只需将名称保存在 try/catch 范围之外的变量中:

      using (SqlConnection myConnection = new SqlConnection(SQLConnectString)) 
      {
           myConnection.Open();
           string txName = "UpdateTransaction";    
           SqlTransaction transaction = myConnection.BeginTransaction(txName);
      
           //The update methods are omitted here for brevity
      
           try 
           {
               logger.Log("Attempt commit ");
               transaction.Commit();
           }
           catch (Exception ex) 
           {
               logger.Error($"Commit transaction {txName} failed - " + ex.Message, ex.StackTrace);
           }    
      }
      

      不理想,因为它创建了一个字符串变量,稍后必须进行垃圾回收,但它完成了工作。

      更新:

      查看reference source,似乎名称没有存储在任何地方,因此无法检索。

      【讨论】: