4

我有一个包含在事务范围内的代码块。我正在使用 LINQ 与数据库进行通信。捕获到死锁异常后,如何重新提交事务?

4

2 回答 2

4

基本上,您只需捕获死锁异常并再次尝试代码。我们做这样的事情:

private static void ExecuteWithDeadlockRetry(int maxAttempts, 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) { maxAttempts = 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 < maxAttempts)
            {
                // Log error here
            }
            else
            {
                throw;
            }
        }
    } while (tryCount <= maxAttempts);
}

电话看起来像这样:

SqlDeadlockHelper.Execute(() =>
{
  // Code to execute here
}

请注意,Execute() 方法最终会调用 ExecuteWithDeadlockRetry()。我们的解决方案比您所要求的要多一些,但这应该会给您一些大致的方向。

于 2012-08-31T23:42:44.530 回答
1

首先思考为什么会发生死锁?是因为您在 LINQ 上下文中读取并修改的值被另一个事务更改了吗?唯一合理的做法是再次读取这些值并确定您的更改是否对新值有意义。由于这是 ASP.NET,这意味着向用户显示新值,因此您必须再次将页面返回给用户,并通知用户发生了更改,并且必须再次编辑数据。

死锁时自动重新提交可能的,但几乎总是一个坏主意。它可能会导致数据库中的错误状态,因为您的域规则被破坏,因为您的重试覆盖了读取值后发生的更改。

于 2012-09-01T06:52:09.683 回答