c#中并发请求api接口
Imagine the following scenario:
想象以下情况:
- User A requests resource 1 via a GET endpoint 用户A通过GET端点请求资源1
- User B requests resource 1 via a GET endpoint 用户B通过GET端点请求资源1
- User A makes changes on resource 1 and saves its changes via a PUT request 用户A对资源1进行更改,并通过PUT请求保存其更改
- User B makes changes on resource 1, on the same fields as user A, and saves its changes via a PUT request用户B在与用户A相同的字段上对资源1进行更改,并通过PUT请求保存其更改
Since users A and B both requested the same version of resource 1, you now have a problem, because the PUT request triggered by user B erased the changes made by user A, and chances are, user A is mad and wondering why his changes do not show up anymore, even though he swears that he did not forget to save. Does that scenario sound familiar ? If so, read on.
由于用户A和B都请求了相同版本的资源1,因此您现在遇到了问题,因为由用户B触发的PUT请求删除了用户A所做的更改,并且很可能用户A生气了,并且想知道为什么他的更改会即使他发誓他不会忘记保存,也不会再出现了。 听起来很熟悉吗? 如果是这样,请继续阅读。
找出问题 (Identifying the problem)
The problem is very simple: users A and B requested a resource more or less at the same time, and got the same version of this resource. Then, they both made changes to the resource in parallel, and whoever saved last erased the changes of the other.
问题非常简单:用户A和B或多或少地同时请求了一个资源,并获得了该资源的相同版本。 然后,他们俩并行地对资源进行了更改,最后保存的人将擦除另一个资源的更改。
There are actually 2 possible ways to solve this issue: through what’s called pessimistic locking or optimistic locking.
解决此问题的方法实际上有两种:通过悲观锁定或乐观锁定。
悲观与乐观锁定 (Pessimistic vs Optimistic locking)
Pessimistic locking means that as soon as a user starts making changes on a resource, he locks this resource. While this resource is locked, no one else can edit this resource. When the user is done with his changes, he unlocks the resource so that other users can retrieve the resource and m