This simple code produces deadlock. Simple Example Program included

后端 未结 3 914
伪装坚强ぢ
伪装坚强ぢ 2021-01-15 17:52

Code, notice the order of the values is different. So it alternates between locking rows:

static void Main( string[] args )
        {
            List

        
3条回答
  •  没有蜡笔的小新
    2021-01-15 18:10

    Your two statements acquire row locks in different order. That's a classic case for deadlocks. You can fix this by ensuring that the order of locks taken is always in some global order (for example, ordered by ID). You should probably coalesce the two UPDATE statements into one and sort the list of IDs on the client before sending it to SQL Server. For many typical UPDATE plans this actually works fine (not guaranteed, though).

    Or, you add retry logic in case you detect a deadlock (SqlException.Number == 1205). This is more elegant because it requires no deeper code changes. But deadlocks have performance implications so only do this for low deadlock rates.

    If your parallel processing generates lots of updates, you could INSERT all those updates into a temp table (which can be done concurrently) and when you are done you execute one big UPDATE that copies all the individual update records to the main table. You just change the join source in your sample queries.

提交回复
热议问题