僵局后重新提交交易 [英] Resubmit transaction after deadlock
本文介绍了僵局后重新提交交易的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有code包裹在一个事务范围的块。我使用LINQ与数据库进行通信。有一次,我捕捉到一个死锁异常,我该如何重新提交的交易?
I have a block of code wrapped in a transaction scope. I'm using LINQ to communicate with the database. Once I capture a deadlock exception, how do I resubmit the transaction?
推荐答案
基本上,你正好赶上了僵局异常,并尝试code了。我们做这样的事情:
Basically, you just catch the deadlock exception and try the code again. We do something like this:
private static void ExecuteWithDeadlockRetry(int maxRetries, bool useTransaction, Action action)
{
int tryCount = 0;
string errorMessage;
// If use transaction is true and there is an existing ambient transaction (means we're in a transaction already)
// then it will not do any good to attempt any retries, so set max retry limit to 1.
if (useTransaction && Transaction.Current != null) { maxRetries = 1; }
do
{
try
{
// increment the try count...
tryCount++;
if (useTransaction)
{
// execute the action inside a transaction...
using (TransactionScope transactionScope = new TransactionScope())
{
action();
transactionScope.Complete();
}
}
else
action();
// If here, execution was successful, so we can return...
return;
}
catch (SqlException sqlException)
{
if (sqlException.Number == (int)SqlExceptionNumber.Deadlock && tryCount < maxRetries)
{
// Log error here
}
else
{
throw;
}
}
} while (tryCount <= maxRetries);
}
和调用看起来是这样的:
And the call looks like this:
SqlDeadlockHelper.Execute(() =>
{
// Code to execute here
}
注意,execute()方法最终会调用ExecuteWithDeadlockRetry()。还有更多的我们的解决方案比你问了一下,但是这应该给你一些大方向。
Note that the Execute() method eventually calls ExecuteWithDeadlockRetry(). There is a bit more to our solution than what you're asking, but this should give you some general direction.
这篇关于僵局后重新提交交易的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文