如何在SQL Server 2005和c#应用程序中消除死锁

本文关键字:应用程序 死锁 SQL Server 2005 | 更新日期: 2023-09-27 18:08:32

我有一个c#的windows服务代码,主要负责更新数据库中表中的记录,但我在日志中总是得到很多错误,所有错误都是关于资源死锁,

错误:

System.Data.SqlClient。SqlException (0x80131904): Transaction (Process . 1904ID 57)在锁资源上与另一个进程发生死锁被选为死锁受害者。重新运行事务。在System.Data.SqlClient.SqlConnection。OnError (SqlException异常,布尔breakConnection,动作1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource完成,Int32超时,任务&的任务,布尔asyncWrite) atSystem.Data.SqlClient.SqlCommand.InternalExecuteNonQuery (TaskCompletionSource"1sendToPipe, Int32超时;布尔asyncWrite) atSystem.Data.SqlClient.SqlCommand.ExecuteNonQuery ()WheelTrackListener.DataAccess.SQLDBA。ExecuteNQuery (SqlCommand cmd,Boolean isShowError, ConnectionStringType, CountryCode, StringdeviceID, Int32 retry, String functionCallName)ClientConnectionId: e45e4cf1-a113-46b7-b9b5-dc5ee8111406

现在,我想问,我可以尝试或检查资源是否被锁定?如果锁定,如何等待更新,直到它被释放?

下面是我当前的代码:

public static int updateVehicleLastPosition(string UTCDate, string UTC_Time, 
              string NS_Indicator, string Latitude, string EWIndicator, 
              string Longtitude, string Speed, string Processed, 
              string Near_ByLocation, string Near_ByLocation_AR, 
              string Gis_dataID, string address, string ar_adress, string Device_ID)
{
        SQLMethods sql = new SQLMethods();
        SqlCommand cmd = sql.cmdUpdateVehicleLastPosition(UTCDate, UTC_Time, NS_Indicator, Latitude, EWIndicator, Longtitude, Speed, Processed, Near_ByLocation, Near_ByLocation_AR, Gis_dataID, address, ar_adress, Device_ID);
        SQLDBA sqlDBA = new SQLDBA();
        return sqlDBA.ExecuteNQuery(cmd, true, ConnectionStringType.OMN, Device_ID, 10, "updateVehicleLastPosition");
}
public SqlCommand cmdUpdateVehicleLastPosition(string UTCDate, string UTC_Time, 
                      string NS_Indicator, string Latitude, string EWIndicator, 
                      string Longtitude, string Speed, string Processed, 
                      string Near_ByLocation, string Near_ByLocation_AR, 
                      string Gis_dataID, string address, string ar_adress, 
                      string Device_ID)
 {
        string sql = "UPDATE CTS_VehicleLastPosition SET [UTCDate] = @UTCDate, [UTC_Time] = @UTC_Time, [NS_Indicator] = @NS_Indicator, [Latitude] = @Latitude, [EWIndicator] = @EWIndicator, [Longtitude] = @Longtitude, [Speed] = @Speed, [Processed] = @Processed, [Near_ByLocation] = @Near_ByLocation, [Near_ByLocation_AR] = @Near_ByLocation_AR, [Gis_dataID] = @Gis_dataID, [address] = @address, [ar_adress] = @ar_adress WHERE [Device_ID] = @Device_ID";
        SqlCommand cmd = new SqlCommand(sql);
        cmd.Parameters.AddWithValue("@UTCDate", UTCDate);
        cmd.Parameters.AddWithValue("@UTC_Time", UTC_Time);
        cmd.Parameters.AddWithValue("@NS_Indicator", NS_Indicator);
        cmd.Parameters.AddWithValue("@Latitude", Latitude);
        cmd.Parameters.AddWithValue("@EWIndicator", EWIndicator);
        cmd.Parameters.AddWithValue("@Longtitude", Longtitude);
        cmd.Parameters.AddWithValue("@Speed", Speed);
        cmd.Parameters.AddWithValue("@Processed", Processed);
        cmd.Parameters.AddWithValue("@Near_ByLocation", Near_ByLocation);
        cmd.Parameters.AddWithValue("@Near_ByLocation_AR", Near_ByLocation_AR);
        cmd.Parameters.AddWithValue("@Gis_dataID", Gis_dataID);
        cmd.Parameters.AddWithValue("@address", address);
        cmd.Parameters.AddWithValue("@ar_adress", ar_adress);
        cmd.Parameters.AddWithValue("@Device_ID", Device_ID);
        return cmd;
}
public int ExecuteNQuery(SqlCommand cmd, bool isShowError, 
                    DataAccess.ConnectionStringType CountryCode, string deviceID, 
                    int retry, string functionCallName)
{
        ConnectionManager Connection = new ConnectionManager();
        try
        {
            Connection.GetConnection(CountryCode);
            if ((Connection.con == null) || (Connection.con.State != ConnectionState.Open))
            {
                if (retry <= 0) return 0;
                else return ExecuteNQuery(cmd, isShowError, CountryCode, deviceID, retry - 1, functionCallName);
            }
            int rowsAffected = 0;
            cmd.Connection = Connection.con;
            rowsAffected = cmd.ExecuteNonQuery();
            return rowsAffected;
        }
        catch (SqlException sqlexception)
        {
            if (isShowError)
                LEAMRALogger.Logger.WriteByDate("Logs''SQLDBA''" + functionCallName + "''" + String.Format("{0:dd-MM-yyyy}", DateTime.Now), "SQLDBA", "SQLDBA_ERROR", "ExecuteNQuery Function: [deviceID: " + deviceID + " | retry: " + retry + "] " + sqlexception.ToString());
        }
        catch (Exception ex)
        {
            if (isShowError)
                LEAMRALogger.Logger.WriteByDate("Logs''SQLDBA''" + functionCallName + "''" + String.Format("{0:dd-MM-yyyy}", DateTime.Now), "SQLDBA", "SQLDBA_ERROR", "ExecuteNQuery Function: [deviceID: " + deviceID + " | retry: " + retry + "] " + ex.ToString());
        }
        finally
        {
            if ((Connection.con != null) && (Connection.con.State == ConnectionState.Open))
            {
                Connection.con.Close();
                Connection.con.Dispose();
            }
            GC.Collect();
        }
        if (retry <= 0) return 0;
        else return ExecuteNQuery(cmd, isShowError, CountryCode, deviceID, retry - 1, functionCallName);
}

如何在SQL Server 2005和c#应用程序中消除死锁

我看不到任何显式的事务范围在你的代码,所以我不知道什么锁已经在地方,当你做你的更新;此外,您使用的隔离级别也不清楚。但是在这种情况下最常见的情况是,在同一事务的早期,您已经对稍后尝试更新的相同行发出了选择(读锁)。这将导致锁升级,如果两个事务试图做同样的事情,则可能导致死锁:

    事务A: select with read lock
  1. 事务B: select with read锁
  2. 事务A: update -希望将其读锁升级到A写锁,但必须等待事务B释放它的读锁
  3. 事务B: update -希望将其读锁升级到a写锁,但必须等待事务A释放它的读锁。

宾果!因为A和B都在等待对方释放他们现有的读锁,然后才能进行更新。

为了防止这种情况,你需要在你的select语句中添加一个updlock提示,例如

select * from table with (updlock) where blah blah

这将确保您的select使用写锁而不是读锁,这将防止并发事务之间的锁升级。

虽然可以检查锁,但不能保证在发出下一条语句时其他进程没有取出锁。按优先顺序排列的可能解决方案:

1)在事务中始终以相同的顺序引用表。

2) @ShellShock的答案

3)捕获死锁错误并处理它