我正在寻找大型业务应用程序中的错误,其中业务流程失败但部分保留到数据库中。更难以弄清楚的是,该过程每隔几周才会失败一次,每次失败之间都会成功处理数十万次。当并发/工作进程数量增加时,错误频率似乎会增加。
到目前为止,我们已经能够通过该程序重新创建我们所看到的内容。 (.NET 4.7.1框架)
using (var transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
using (var sqlConnection = new SqlConnection("Server=localhost;Database=Database1;Trusted_Connection=True"))
{
sqlConnection.Open();
// Doing some unwanted nested manual transaction and rolling it back
var transaction = sqlConnection.BeginTransaction();
new SqlCommand($"INSERT INTO TestTable VALUES('This will be rolled back}')", sqlConnection).ExecuteNonQuery();
transaction.Rollback();
// Now doing some work with the DB.
// You might expect it to become a part of transactionScope, but that is NOT the case!
// So this command will actually succeed, with data written to the DB.
new SqlCommand($"INSERT INTO TestTable VALUES('This will be inserted')", sqlConnection).ExecuteNonQuery();
// Doing something which promotes the local transaction to a distributed transaction.
using (var sqlConnection2 = new SqlConnection("Server=localhost;Database=Database2;Trusted_Connection=True"))
{
// The program will fail here, with message "The transaction has aborted, Failure while attempting to promote transaction."
sqlConnection2.Open();
new SqlCommand($"INSERT INTO TestTable2 VALUES('We will never come this far')", sqlConnection2).ExecuteNonQuery();
}
}
transactionScope.Complete();
}
我们的生产代码没有明确调用transaction.Rollback()
,在我的示例中,它只是作为重现错误消息和行为的手段。但如果我们的任何第三方库进行此调用,我想抛出异常并尽快退出。最好是在应用层。
我怎样才能检测到调用Rollback()
已经做了?我真的不想在不确定的情况下进行粗略操作transactionScope
能够完成它的工作。
Update 1
我不想要的“回滚”是由 .Net 连接共享机制中的某个错误引起的。该错误在 4.5.1 和 4.8 之间的所有 .Net Framework 版本以及新版本上都会重现。System.Data.SqlClient包.
An 问题已添加到 System.Data.SqlClient 存储库中.