How to get rid of deadlock in a SQL Server 2005 and C# application?

旧巷老猫 提交于 2019-12-04 09:58:28
Polyfun

I can't see any explicit transaction scope in your code, so I do not know what locks are already in place when you are doing your update; also it is not clear what isolation level you are using. But the most common scenario in this type of situation is that earlier in the same transaction you have issued a select (read lock) on the same rows that you are trying to update later. This will cause a lock escalation, and can result in a deadlock if two transactions are trying to do the same thing:

  1. Transaction A: select with read lock
  2. Transaction B: select with read lock
  3. Transaction A: update - wants to escalate its read lock to a write lock, but has to wait for transaction B to release its read lock
  4. Transaction B: update - wants to escalate its read lock to a write lock, but has to wait for transaction A to release its read lock.

Bingo! deadlock as both A and B are waiting on each other to release their existing read locks before they can do their update.

To prevent this you need an updlock hint in your select, e.g.,

select * from table with (updlock) where blah blah

This will ensure your select uses a write lock instead of a read lock, which will prevent lock escalation between concurrent transactions.

Although it's possible to check for a lock you cannot guarantee that by the time the next statement is issued some other process hasn't taken out a lock. Possible solutions in order of preference:

1) Always reference tables in the same order within trancations.

2) @ShellShock's answer

3) Trap the deadlock error and handle it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!