How to handle the concurrency problems on ASP.Net
2024-07-10 12:56:16
供稿:网友
<数据唯一性>
acid中重要的一个环节: data isolation
data isolation
creating fully-isolated transactions in a multithreaded environment is a non-trivial exercise. there are three ways isolation can be violated:
lost update: one thread reads a record, a second thread updates the record, and then the first thread overwrites the second thread's update.
线程1读了一条记录,线程2更新了一条记录,接着线程1覆盖了线程2的更新。dirty read: thread one writes data; thread two reads what thread one wrote. thread one then overwrites the data, thus leaving thread two with old data.
线程1写入了数据,线程2读取了线程1所写入的数据。线程1更改了数据,最后线程2读取的是没有更新的旧数据。unrepeatable read: thread one reads data; the data is then overwritten by thread two. thread one tries to re-read the data but it has changed.
线程1读去了数据;但是此数据接着被线程2修改了。线程1试图从新读取数据,但是数据已经被修改了。
solution for multiuser updates:
to prevent this kind of problem, you may use any of the following strategies:
step1: locking the records. when one user is working with a record, other users can read the records but they cannot update them. 锁定要修改的记录。
app: you would need to write monitoring processes that keep track of how long records have been locked, and unlock records after a time-out period.step2:updating only the columns you change. in the previous example, qa would have changed only the owner and the status, while the developer would have changed only the description.
只更新你要修改的列.
app: comparing original against new,this method involves creating an event handler for the rowupdating event. the event handler examines the original value of each field and queries the database for the value currently in the database. step3:previewing whether the database has changed before you make your updates. if so, notify the user. 预先检查一下在执行更新之前数据库是否已经被修改了,如果是这样的话,通知用户。step4:attempting the change and handling the error, if any.
处理更改和错误。
app: the best approach to managing concurrency is to try the update and then respond to errors as they arise.this approach has tremendous efficiency advantages.for this approach to work, your stored procedure for updates must fail if the data has changed in the database since the time you retrieved the dataset. since the dataset can tell you the original values that it received from the database, you need pass only those values back into the stored procedure as parameters, and then add them to the where clause in your update statement,