NGWS SDK Documentation  

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

8.12 The lock statement

The lock statement obtains the mutual-exclusion lock for a given object, executes a statement, and then releases the lock.

lock-statement:
lock ( expression ) embedded-statement

The expression of a lock statement must denote a value of a reference-type. An implicit boxing conversion (§6.1.5) is never performed for the expression of a lock statement, and thus it is an error for the expression to denote a value of a value-type.

A lock statement of the form

lock (x) ...

where x is an expression of a reference-type, is precisely equivalent to

System.CriticalSection.Enter(x);
try {
   ...
}
finally {
   System.CriticalSection.Exit(x);
}

except that x is only evaluated once. The exact behavior of the Enter and Exit methods of the System.CriticalSection class is implementation defined.

The System.Type object of a class can conveniently be used as the mutual-exclusion lock for static methods of the class. For example:

class Cache
{
   public static void Add(object x) {
      lock (typeof(Cache)) {
         ...
      }
   }
   public static void Remove(object x) {
      lock (typeof(Cache)) {
         ...
      }
   }
}