CS.PROP.LOCK

Lock both when either set or get is locked for a property.

This rule triggers whenever a property has both get and set methods and one of the following conditions holds:
  • Only one of the methods uses a lock and the other does not.
  • Both of them use lock, but lock on different objects.

Vulnerability and risk

If one of the methods in a property requires a lock, then it is very likely that the other one also needs it. Not locking can lead to issues that are very hard to detect and debug since the issues are usually not easy to reproduce.

Vulnerable code example

Copy
  //VIOLATION CASE
  public class Class1
  {
      private object a;
      private object DeadBolt = new object();
      public object SomeObject
      {
          get
          {
             lock (DeadBolt)
             {
                 return a;
             }
         }
         set
         {
             a = value;
         }
     }
 }

Fixed code example

Copy
  //FIXED CASE
  public class Class1
  {
      private object a;
      private object DeadBolt = new object();
      public object SomeObject
      {
          get
          {
             lock (DeadBolt)
             {
                 return a;
             }
         }
         set
             {
             lock (DeadBolt)
             {
                 a = value;
             }
         }
     }
 }