如果 DbTransaction 的 Commit() 或 Rollback() 抛出异常,如何处理?

Chu*_*ati 2 c# sql-server transactions

我正在使用 Visual Studio 2012 和 MS SQL Server 2008 R2。

在我的代码中,我使用DbConnectionDbTransaction。这是我的代码:

DbConnection dbConnection = null;
DbTransaction dbTransaction = null;

try
{
   dbConnection = DbProviderFactories.GetFactory("System.Data.SqlClient").CreateConnection();
   dbConnection.ConnectionString = connectionString;
   dbConnection.Open();
   dbTransaction = dbConnection.BeginTransaction();
   // do my work using dbConnection and dbTransaction
   dbTransaction.Commit();
} 
catch (MyWorkFailedException mwfe)
{
   dbTransaction.Rollback();
   throw;
}
finally
{
   if (dbConnection != null)
   {
      dbConnection.Close();
      dbConnection.Dispose();
   }
}
Run Code Online (Sandbox Code Playgroud)

是否有可能dbTransaction.Commit();dbTransaction.Rollback();抛出一个异常?

如果是,那么如何在我的代码中处理它?c# 程序员通常如何处理这种情况?或者他们不处理这种情况?

Rob*_*Rob 5

Yes, both Commit and Rollback can throw exceptions. However, these should probably be propagated up and either logged or displayed as an error to the user. How you want to handle the error is entirely up to you, but typically the errors will be due to a closed connection. Secondly, you should leverage using

using (var dbConnection  = DbProviderFactories.GetFactory("System.Data.SqlClient").CreateConnection())
{
    dbConnection.ConnectionString = connectionString;
    dbConnection.Open();
    using (var dbTransaction = dbConnection.BeginTransaction())
    {
        //Do work here

        dbTransaction.Commit();
    }
}
Run Code Online (Sandbox Code Playgroud)

DbTransaction will automatically rollback on its dispose method (assuming it hasn't been committed). Exceptions thrown by this code typically are not something you can gracefully handle. For the most part, they would come from SQL errors (invalid syntax, FK errors, etc), or a closed connection.

As long as you've got a good logging system in place, the above code should be all you need.