【问题标题】:Deadlock executing Query in Sql Server在Sql Server中执行查询死锁
【发布时间】:2017-06-26 16:21:56
【问题描述】:

我有以下 Linq:

var qry = s.GetTable<MessageEventDTO>().Where(x => x.MessageName == messageName && x.SourceTyp == sourceTyp && x.Source == source && (x.Status == MessageEventStatus.open || x.Status == MessageEventStatus.acknowledged));

goneMessages = qry.ToList();

var ret = qry
    .Set(x => x.Status, x => x.Status | MessageEventStatus.gone)
    .Set(x => x.TimestampGone, timeStamp)
    .Update();
return ret;

这将被转换为以下SQL:

UPDATE MessageEvents SET Status = Status | 1, TimeStampGone = @1
WHERE MessageName = @2 AND SourceTyp = @3 Source = @4 AND (Status = 0 OR Status = 2)

现在的问题是,有多个Update并行运行,出现死锁异常,不明白为什么?

另见

【问题讨论】:

  • 你的桌子上有什么索引?索引调优通常可以避免死锁。
  • 您是否在代码中打开交易?我认为当你不使用事务时不应该发生这种情况......

标签: c# sql-server linq deadlock


【解决方案1】:

如果您不希望其他进程能够启动更新的选择部分,请使用UPDLOCK 提示或设置适当的事务隔离级别 (REPEATABLE READ)。

请参阅John Huang's Blog,以更全面地了解非聚集索引如何导致死锁。

使用不受此问题影响的 Linq to SQL 的示例:

var opts = new TransactionOptions();
opts.IsolationLevel = IsolationLevel.RepeatableRead;
using (var txn = new TransactionScope(TransactionScopeOption.Required, opts))
{
    // update command goes here.

    txn.Complete();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-03
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多