C# multithreaded lock

Background: In another test, the user and I operated the system at almost the same moment (I don't know who came first, the estimated interval is in milliseconds).

The operation log displayed in the feedback from the user is my login information. So start looking for the problem. First of all, the reason why global variables are overwritten by successive operations is ruled out. First log in with account A, then log in with account B using a different browser, and then use the operating system of account A. In this case, A’s identity information is obtained according to A’s token, and B’s token information is obtained from B’s token. There will be no global user Problem with information variables being overwritten. Then there is only one answer, that is, A and B operate at the same time, and use the global variable of user information at the same time. Yes, this is called concurrency.

The following is the use of multithreading + locks to solve concurrency. The core idea is to lock the user's global variables within a certain period of time (5 seconds). Release after 5 seconds. The following is my code, as shown in the figure:

 

lock statement

The lock keyword marks a block of statements as a critical section by acquiring a mutex lock on a given object, executing the statement, and then releasing the lock. The form of this statement is as follows:

Object thisLock = new Object(); lock (thisLock) { // Critical code section }

Monitor class

When multiple threads use an object at the same time, problems similar to common code will also appear. At this time, the lock keyword cannot be used, and the Monitor class in System.Threading needs to be used. resource scheme. It can lock an object, and a thread can only operate on the object if it obtains the lock. The object locking mechanism ensures that only one thread can access the object at the same time, which may cause confusion. The method of use is as follows:

Object o = new Object();

Monitor.Enter(o);

//The current thread can operate the o object

Monitor.Exit(o);

For any object locked by Monitor, some information related to it is stored internally:

One is a reference to the thread that currently holds the lock;

The second is a reserve queue, which stores threads that are ready to acquire locks;

The third is a waiting queue, which holds the external use of the queue that is currently waiting for the state of this object to change.

Guess you like

Origin blog.csdn.net/qq_26695613/article/details/129731680