In some nasty occasions, we find this kind of exceptions after a batch of transactions has been executed in sql server:
Transaction (Process ID 78) was deadlocked on lock resources with another
process and has been chosen as the deadlock victim. Rerun the transaction.
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Transaction (Process
ID 78) was deadlocked on lock resources with another process and has been
chosen as the deadlock victim. Rerun the transaction.
There is a quite complete article on the subject by Ron Talmage. I just cite some important statements:
"Lock-based deadlocks involve two or more threads, at least one transaction, and one or more resources. It's useful to view deadlocks as occurring in two stages. The first is a grant stage, where each thread is granted a lock on its resource.[...]The second stage is a blocked request where each thread requests an incompatible lock on the other thread's resource. Each thread waits on the other to release its locks before it can complete."
When SQL Server finds deadlocks, it proceeds to choose one of the threads as the "victim" and kills it (well, rols back its transaction).
The article explains 4 main ways to solve deadlocks:
- Remove incompatible lock requests
- Change the timing of transactions
- Change the order of resource requests
- Change the isolation leve
The last one, changing the isolation level, seems to be the only way in some cases. For example, if we allow queries to read uncommitted data, we can set the level as follows:
SET ISOLATION LEVEL READ UNCOMMITTED
So next time you have one of those, this article might help.