The lock statement takes the mutex of a given object, executes a statement block, and then releases the lock. When holding a lock, the thread holding the lock can acquire and release the lock again. Any other thread is blocked from getting the lock and waits until the lock is released.
Review:
Use the lock code
Equivalent to
It can be thought that the underlying code of Lock is implemented by Monitor.
Since the code uses try... finalblock, so even if an exception is thrown in the body of the lock statement, the lock is released.
You cannot use the await operator lock in the body of the statement.You cannot use it in the body of the statementawaitoperator lock。 You cannot use the await operator lock in the body of the statement. You cannot use the await operator lock in the body of the statement. This sentence is very important!
Documentation:The hyperlink login is visible.
I test the code myself,Use Task to get the lock and use await to block, the code is as follows:
After executing the following code several times, the execution result is not as expected.
Why? If you try to use the await keyword when trying to use the await keyword in the lock block, you will get this compilation error: cannot await in the body of a lock statement. The reason is that after await is completed, the method may run in a different thread instead of the thread (calling thread) before the await keyword.lockkeywordsame threadGet lock and release lock in the lock。 Modify the code to see the reason more intuitively:
Get the thread id of the lock and the thread id of the lock release,Obviously not on a thread, so the lock cannot be successfully released, as shown in the figure below:
Tried modifying the code, tested with thread, executed multiple times, and it worked as expected, the code is as follows:
(End)
|