Optimistic Concurrency Control:?
- Optimistic Concurrency assumes that conflicts will be rare and allows multiple
users to read and modify data without locking it.
- When updating data, you compare the current data in the database with the data the
user fetched earlier (usually by checking a timestamp or version number). If the data
has been changed by someone else, you throw a concurrency exception.
Steps:
- Add a timestamp or row version column to the table.
- When updating, check if the timestamp or row version has changed.
Example:
SqlCommand command = new SqlCommand("UPDATE Customers SET
CustomerName = @CustomerName WHERE CustomerID = @CustomerID AND
RowVersion = @RowVersion", connection);
command.Parameters.AddWithValue("@CustomerName", customerName);
command.Parameters.AddWithValue("@CustomerID", customerId);
command.Parameters.AddWithValue("@RowVersion", rowVersion);
Follow:
If the RowVersion has changed between the time the user fetched the data and the time
they attempt to update, the update will fail, and an exception will be thrown.