使用读/写锁来保护表?
您可以通过多种方式实现乐观锁定,但实现乐观锁定的基础保持不变。这是一个 4 步过程,如下所示:-
• Record the current timestamp.
• Start changing the values.
• Before updating check whether anyone else has changed the values by checking the old time stamp and new time stamp.
• If it’s not equal rollbacks or else commit.
我们可以通过 3 种主要方式在 .NET 中实现乐观锁定:-
• Datasets: - Dataset by default implement optimistic locking. They do a check of old values and new values before updating.
• Timestamp Data type: - Create a timestamp data type in your table and while updating check if old timestamp is equal to new timestamp.
• Check old and new value: - Fetch the values, do the changes and while doing the final updates check if the old value and current values in database are equal. If they are not equal then rollback or else commits the values.
锁定模式:
Shared:
Used for read operations that do not change or update data, such as a SELECT statement.
Update:
Used on resources that can be updated. Prevents a common form of deadlock that occurs when multiple sessions are reading, locking, and potentially updating resources later.
Exclusive:
Used for data-modification operations, such as INSERT, UPDATE, or DELETE. Ensures that multiple updates cannot be made to the same resource at the same time.
Intent:
Used to establish a lock hierarchy. The types of intent locks are: intent shared (IS), intent exclusive (IX), and shared with intent exclusive (SIX).
Schema:
Used when an operation dependent on the schema of a table is executing. The types of schema locks are: schema modification (Sch-M) and schema stability (Sch-S).
Bulk Update:
Used when bulk copying data into a table and the TABLOCK hint is specified.
Key-range:
Protects the range of rows read by a query when using the serializable transaction isolation level. Ensures that other transactions cannot insert rows that would qualify for the queries of the serializable transaction if the queries were run again.
另外这篇文章应该会有所帮助。