|
The lock keyword marks a block of statements as a critical zone by taking a mutex for a given object, executing the statement, and then releasing the lock.
The lock statement basically uses Monitor.Enter and Monitor.Exit, that is, Monitor.Enter(this) is executed when lock(this) is executed, and Monitor.Exit(this) is executed at the end of the curly brace. What is its meaning, for any object, the first part of the memory is the address of all methods, and the second part is an index. He points to a SyncBlock in the SyncBlock Cache area of the CLR. What does that mean? That is, when you execute Monitor.Enter(Object), if the index value of the object is negative, select a SyncBlock from the SyncBlock Cache and place its address in the index of the object. This completes the lock marked by object, and the other threads want to perform the Monitor.Enter(object) operation again, which will get an index with a positive object, and then wait. Until the index becomes negative, i.e. the thread uses Monitor.Exit(object) to turn the index negative. What you need to pay attention to when using lock:
1.lock cannot lock null value An object can point to null, but null does not need to be released. (See also: Understanding Full Null) 2.lock cannot lock the string type, although it is also a reference type. Because the string type is "hovered" by the CLR This means that there is only one instance of any given string in the entire program, and that same object represents that text in all threads of all running application domains. Therefore, as long as a lock is placed on a string with the same content anywhere in the application process, all instances of that string in the application will be locked. Therefore, it is best to lock private or protected members who will not be persisted. 3.locklock the object is the memory boundary of a program block 4. The value type cannot be locked, because the "object is released" in red in the previous text, and the value type is not a reference type 5.lock avoids locking public types or objects that are not controlled by the program. For example, if the instance is publicly accessible, lock(this) can be problematic because uncontrolled code can also lock the object. This can lead to deadlocks, where two or more threads wait to release the same object. Locking public data types (as opposed to objects) can also cause problems for the same reason. When using lock(this), the value of the class member variable may be changed by the method that is not in the critical zone
Application scenario: It is often used to prevent uncertain exceptions in the value of public variables caused by multi-threaded operations to ensure the security of operations
|