SoFunction
Updated on 2025-03-06

Detailed explanation of the usage of thread synchronization lock keyword in C#

1. The lock keyword ensures that a code block will not be disturbed by other threads during execution. This is achieved by adding a mutex to a specific object during the execution of the code block.

2. The parameters of the lock keyword must be an object of reference type. lock is invalid for basic data types such as int, long, etc., because the type it acts as must be an object. If long-type data is passed in, it will inevitably be converted to Int64 structure type, then the locked object reference is a brand new object reference. If you need to restrict them by mutually exclusive access, you can use the methods provided by the class, which provides atomic operations.

3. Use lock(this) with caution. Use lock(this) in common types. If a new object is created and locked, it is very easy to cause deadlocks.

4. When locking an ICollection type object, its SyncRoot property should be locked.

The SyncRoot property is declared in the interface ICollection, and its implementation methods are different.

For example, in Collection(), the following is implemented:

object  
{ 
     get 
     { 
          if (this._syncRoot == null) 
          { 
               ICollection items =  as ICollection; 
               if (items != null) 
               { 
                    this._syncRoot = ; 
               } 
               else 
               { 
                    (ref this._syncRoot, new object(), null); 
               } 
          } 
          return this._syncRoot; 
     } 
} 

And in List<T>, ArrayList and other classes, it is implemented as follows:

object  
{ 
     get 
     { 
          if (this._syncRoot == null) 
          { 
               (ref this._syncRoot, new object(), null); 
          } 
          return this._syncRoot; 
     } 
} 
  

In the Array class, this is directly returned:

public object SyncRoot 
{ 
     get 
     { 
          return this; 
     } 
} 

5. The lock keyword is implemented using the Monitor (management program) class.

lock(x) 
{ 
  DoSomething(); 
} 

 obj = ()x; 
(obj); 
try 
{ 
  DoSomething(); 
} 
finally 
{ 
  (obj); 
} 

The above two codes are equivalent. (MSDN)

Using the lock keyword is simpler and safer than the Monitor class.