Assume that houses have occupants and that no two occupants of any house can have the same height.
- Pick a random house
- Get a list of the current occupants of the house
- Decide which ones to keep, replace, evict, or add by examining the list
- Make sure that the new list doesn't contain any occupants of the same height.
- Replace the existing list with the new list; delete, insert, or update as required.
Sounds simple enough but when you have 50 threads all trying to do this at the same it gets complicated. I used UPDLOCK, ROWLOCK on the select (step 2) to block possible updates to any of the occupants I might want to update. I get an occasional failure, however, when there are no current occupants and a new occupant is added. The failure is always a unique constraint violation. This should never happen (see step 4) but it does.
Steps 2-5 are being performed within a TransactionScope using ReadCommitted isolation level.
Is there a best practices model somewhere that defines how a scenario like this should be handled?