简体   繁体   中英

Deadlock executing Query in Sql Server

I've the following 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;

which will be converted to following SQL:

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

the problem is now, there are multiple Updates run in parallel, and I got deadlock exceptions, but I do not understand why?

see also
在此处输入图片说明

在此处输入图片说明

If you don't want another process to be able to start the select portion of the update, use the UPDLOCK hint or set an appropriate transaction isolation level ( REPEATABLE READ ).

See John Huang's Blog for a more thorough explanation of how nonclustered indexes can cause deadlocks.

Example using Linq to SQL which is not prey to this issue:

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

    txn.Complete();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM