4

我想阻止两个用户在更新记录时意外地相互覆盖。也就是说,两个用户加载了一个带有记录 A 的页面。用户一将记录更新到 AB,用户二将记录更新到 AC。

我不只是希望最后一个命中数据库来覆盖。我需要一种机制来说明记录已更新,因此您的记录无法保存。

现在我有两个想法是给记录加时间戳并检查。如果不匹配,则不允许更新。第二种方法是每次执行更新时对记录进行 GUID,检查 GUID,如果不匹配则不更新。

这些方法中的任何一个是否有效,如果是,那是最好的。如果没有,你有什么建议。如果它有所作为,这在 C# 中

谢谢

4

6 回答 6

11

The two methods you've mentioned are effectively equivalent - either way you've got a unique identifier for "the record at the checkout time" effectively. I don't have any particular view on which is better, although a timestamp obviously gives you the added benefit of data about when the record was valid.

An alternative is to remember what the previous values were, and only allow an update if they match - that way if user A started editing a record, then user B goes in and changes something, then changes it back, user A's edits are still valid.

The term for these techniques is optimistic locking (or optimistic concurrency control).

于 2010-02-22T10:09:16.510 回答
5

There is actually a third method. To do the update, issue an update statement of this form:

UPDATE table SET update_field = new_value
WHERE db_pk = my_pk       // assume primary key immutable
AND update_field = original_field_value

where original_field_value is the value of the field before the update was attempted. This update will fail if someone else has modified update_field, unless they have changed it to the same value that you have.

于 2010-02-22T10:10:12.183 回答
4

You're describing Optimistic Locking, a valid and useful technique.

See references here.

于 2010-02-22T10:09:42.603 回答
2

Either method is valid for checking.

As to which is the best you have to look at the size of your app and how long it will take to implement each one. So if this is only ever going to happen occasionally then I'd prob go for the quicker solution and implement the timestamp option.

If you want something more detailed google concurrency - heres an article to start with - concirrency

于 2010-02-22T10:10:34.650 回答
1

I am using the first option. Update the timestamp on each update. So at the time of update we check the equality of the timestamp.

于 2010-02-22T10:09:41.817 回答
0

乐观和悲观的术语是否敲响了警钟。这是解决您所描述问题的两种公认方法。听起来您在 Web 环境中工作。在这种情况下,前一个选项(乐观锁定)更合适。您已经继续描述了这通常是如何实现的。通常使用时间戳或版本号来检查自检索记录以来记录是否已更新。要考虑的另一件事是让您的用户知道基础数据发生了变化,并可能让他们选择在他们尝试保存的内容和其他用户保存的内容之间进行选择。这种选择实际上取决于业务规则是什么。

于 2010-02-22T10:13:57.440 回答