gpt4 book ai didi

c# - TransactionAbortedException - 你能安全地重新运行吗?

转载 作者:太空狗 更新时间:2023-10-29 20:33:08 25 4
gpt4 key购买 nike

我按以下方式使用 TransactionScope

using (var scope = new TransactionScope())
{
using (var conn = SQLHelpers.GetSQLConnection())
{
//commands here
}
scope.Complete();
}

有时我在调用 scope.Complete() 时收到 TransactionAbortedException,因为事务已经回滚,我已经使用探查器确定问题是死锁。

Exception Transaction (Process ID 59) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

我已经找到了死锁的原因,但它让我想知道为什么这个错误没有冒泡到 TransactionAbortedException 所以我确实可以为那个特定的情况重新运行事务。 内部异常不包含任何可以指示实际错误的信息。

TransactionAbortedException 检测为重新运行事务的原因是否安全?

到目前为止,我已经看到了以下内部异常:

1)死锁
2)超时
3) '连接已关闭'
4) .. 其他 ?

在其中只有一种情况下,重新运行事务似乎是合适的,但是如果可以保证回滚,则可以将其推广到所有情况。问题可以重新表述为“TransactionAbortedException 是否保证事务被回滚”?

最佳答案

The question could be re-stated to ask 'does a TransactionAbortedException guarantee the transaction was rolled back'?

TransactionAbortedException 的文档说:

This exception is thrown when an action is attempted on a transaction that has already been rolled back, for example, when you attempt to call the Commit method on a transaction that has already timed out. This exception is also thrown when an attempt is made to commit the transaction and the transaction aborts.

This is a recoverable error.

我认为从这个描述中可以很清楚地看出,如果您捕获到这个异常,那么您的交易由于某种原因没有成功完成。我对文档的理解是:“事务试图做的任何更改都没有提交给数据库”。

“这是一个可恢复的错误”,所以如果您的事务的性质是重试它是有意义的,那么您应该在捕获此异常后重试。

你可能想引入一些关于重试的逻辑,比如在重试之前等待一段时间。并随着重试次数的增加增加这个等待时间。对总重试次数或总重试时间进行限制,并在所有重试尝试失败时优雅地做一些明智的/失败的事情。

关于c# - TransactionAbortedException - 你能安全地重新运行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40169213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com