Defined
Lock keyword, a mutex, that sets the code inside the statement block ({}) to a critical section by locking an object.
If a thread encounters a mutex when executing code linearly, it must first request access to the mutex and, if successful, continues to linearly access the critical section code block after the mutex. The statement reads as follows:
1 New Object (); 2 Lock (Thislock) 3 {4 // Critical Code section. 5 }
The lock keyword ensures that when one thread is in the critical section of the code, the other thread does not enter the critical section. If another thread attempts to enter the locked code, it waits (that is, is blocked) until the object is freed.
Use
Locked objects cannot be of the public type, or lock ( this),Lock (typeof (MyType)), and lock ("MyLock") use are not compliant.
Lock objects do not affect external thread code only if they are not externally accessed. Becausethis,typeof (MyType) in lock (this), Lock (typeof (MyType)) and lock ("MyLock") is potentially externally accessible, external code with the same string as "MyLock" These objects are locked and have unpredictable effects on the process code. Therefore, it is recommended to use the private object as the lock object.
C#_ Keyword: The interpretation and use of lock