Common misuse scenarios: In order to prevent duplicate payment of orders caused by users accidentally clicking the payment button multiple times, we use lock (order number) to ensure that only one thread is allowed to perform the operation on the order.
This idea is good, at least better than lock (a private static object for processing classes), because the effect of locking order number is to lock only the operation of the current 1 order, and if lock static variable, that is to lock all orders, will cause all orders to be queued, which is obviously unreasonable.
So can the lock (order number) method mentioned at the beginning of this article achieve the desired effect? Let's use some code to restore the usage scenario first.
If you ignore user information and other validations, the code looks pretty much like this:
For the lock keyword, MSDN includes information that can be found on Baidu, and it seems that it is recommended not to use lock(string), and the reason is the same. The following passage is taken from MSDN's advice on lock strings:
The lock("myLock") issue occurs because any other code using the same string in the process will share the same lock. This sentence hides a huge mechanism, that is, "the same string".
What is "the same string"? See the code:
Are str1 and str2 the same string above? The answer is YES.
See again:
Are str1 and str2 above still the same string? The answer is NO.
Okay, let's go back to the issue of our order payment. In our code, lock(orderNumber), when the user accidentally clicks a few more times after swiping his hand, is the orderNumber entering this action the same string each time? The answer is NO. This is to say
The code that handles the order above doesn't actually act as a lock.
In fact, there are two types of string comparisons, see the code:
The first line of the above code outputs True, and the second line outputs False. I believe you understand what MSDN means by "the same string" without my explanation.
The best solution
Solutions for optimal locking strings:
Demo code:
In the website, sometimes a global variable may be used, this global variable, when multiple users access at the same time, may appear abnormal, at this time, we will set a global lock, but the disadvantage of this is that all accesses will wait in turn.
In some scenarios, for example, the same user can only comment once within 15 seconds, if the global lock is used, the comment function will be very slow to process when the number of users surges, which will greatly affect the user experience.
At this time,We can set the lock for each user individually, lock(string){...}, and the name of the lock can be defined as:Method name + user's IDIn this way, each user has an independent lock, and when judging the comment interval, it will not affect other users' comments.
(End)
|