死锁在SQL中的锁定资源

时间:2018-07-16 08:58:51

标签: c# sql sql-server deadlock database-deadlocks

我正在Windows应用程序中工作c#MultiThread Functionity(5线程)超过2M的数据同时使用我的内部代码删除时突然发生死锁错误,有助于如何纠正和解决问题 错误:事务(进程ID 59)与另一个进程在锁定资源上死锁,因此被选为死锁受害者。重新运行交易

我参考网站并找到一个查询来解决此问题,在这里我提到了该查询,但有时它无法正常工作 SQL: ALTER DATABASE DBName 设置READ_COMMITTED_SNAPSHOT并立即回滚 开始

帮助如何解决该问题,无论是在代码管理还是sql管理中,我都应该更改

代码

if (SqlCon.State == ConnectionState.Closed)
{
   OpenConnection();
}

string sqlStmt = "Delete em from Order em inner join OrderHeader ch on ch.CartonId=em.CartonId and ch.OrderNumber = " + "'" + OrderNumber + "'";
SqlCmd.CommandText = sqlStmt;

SqlCommand.CommandTimeout = TimeoutPeriod();
SqlTransaction transaction;

// Start a local transaction.
transaction = SqlCon.BeginTransaction(IsolationLevel.ReadCommitted);

// Must assign both transaction object and connection
// to Command object for a pending local transaction
SqlCommand.Connection = SqlCon;
SqlCommand.Transaction = transaction;

try
{

   int val = SqlCommand.ExecuteNonQuery();

   // Attempt to commit the transaction.
   transaction.Commit();
   return true;
}
catch (Exception ex)
{
   throw ex;
}
finally
{
   CloseConnection(SqlCon);
}

1 个答案:

答案 0 :(得分:0)

READ_COMMITTED_SNAPSHOT数据库选项将有助于避免与读者和作家而不是作家和作家(并发DELETE语句)被阻止/解除锁定。

在下面运行此查询,以获取system_health跟踪中的最新死锁详细信息:

WITH
      CurrentSystemHealthTraceFile AS (
        SELECT CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') AS FileName
        FROM sys.dm_xe_session_targets
        WHERE
            target_name = 'event_file'
            AND CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') LIKE '%\system[_]health%'
    )
    , AllSystemHealthFiles AS (
        SELECT 
            REVERSE(SUBSTRING(REVERSE(FileName), CHARINDEX(N'\', REVERSE(FileName)), 255)) + N'system_health*.xel' AS FileNamePattern
        FROM CurrentSystemHealthTraceFile
        )
    , DeadLockReports AS (
        SELECT CAST(event_data AS xml) AS event_data
        FROM AllSystemHealthFiles
        CROSS APPLY sys.fn_xe_file_target_read_file ( FileNamePattern, NULL, NULL, NULL) AS xed
        WHERE xed.object_name like 'xml_deadlock_report'
    )
SELECT TOP 10
      DATEADD(hour, DATEDIFF(hour, SYSUTCDATETIME(), SYSDATETIME()), event_data.value('(/event/@timestamp)[1]', 'datetime2')) AS LocalTime
    , event_data AS DeadlockReport
FROM DeadLockReports;

通常可以避免死锁与查询和索引调整有关,因此仅触摸任务所需的那些行。在这种情况下,Order.CartonID上的索引 以及在OrderHeader(OrderID,CartonID)上的复合(理想唯一)索引看起来很有用。

另外,使用与列数据类型匹配的OrderID参数类型对查询进行参数化。