Code, notice the order of the values is different. So it alternates between locking rows:
static void Main( string[] args )
{
List
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.