SQL死锁 - 为什么

时间:2015-08-06 08:52:57

标签: sql-server

对SQL不太了解,但我的网络应用似乎抛出了更多像

这样的错误
Exception: System.Data.Entity
An error occurred while reading from the store provider's data reader. See the inner exception for details.
System.Data.SqlClient.SqlException (0x80131904): Transaction (Process ID 68) was deadlocked on lock | communication buffer resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

这些错误的根本原因是什么?

1 个答案:

答案 0 :(得分:2)

您可以使用此查询来查找历史死锁(带有查询):

SELECT CAST(xet.target_data as XMl) as xe_content
FROM sys.dm_xe_session_targets AS xet
join sys.dm_xe_sessions AS xes ON xes.address=xet.event_session_address
WHERE xes.name='system_health'

您似乎使用EntityFramework(System.Data.Entity)。如果要在代码中捕获事务异常,可以通过以下方式了解是否遇到了死锁异常。然后,您可以进行特定处理(无论如何都要运行交易,......)

if (_exception != null)
{
  if (_exception is EntityCommandExecutionException || _exception is UpdateException)
  {
    if (_exception.InnerException != null)
    {
      if (_exception.InnerException is SqlException)
      {
        if (((SqlException)_exception.InnerException).Number == 1205)
        {
          //This is a deadlock exception via EntityFramework
        }
      }
    }
  }
}