I have an automation project having a remote database (MsSql) and multiple windows/web clients. Client applications check and select a suitable row on a table and mark it as reserved for operating on that row.
- How can I easily get value and update a selected row before another client selects same row? What options do I have for that?
- Can I use
TransactionScopefor that purpose if I want to do more than one select-update statement (for different tables) inside transaction block?
EDIT:
Let’s imagine a cinema ticket system (mine is a little bit more complicated). The user selects a seat and buys ticket. I want to reserve the seat to this user for two minutes to give enough time for buying. After two minutes it will be also available to others. Before updating the row I run a select query to find the first empty seat. My question is about a little time between a select and update statement of same user. I want to prevent: User1’s select statement runs and at that time User2 runs same select before User1 reserves the seat.
Since you want user input between locking and performing actual action, then
In this case you don’t start a transaction before doing this, because you want to commit the change immediately. You may open a transation later, as soon as you lock a row, or at an even later point.
If you do that from a transaction, then the other processes will wait until you commit that transaction, so you will not get any concurrency. What you will then see is, one process working, all others waiting.
When you later come back to the locked row, you verify that time_locked is still non-null, and the user who locked is the same user: