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: The expression of a lock statement must denote a value of a type known to be a reference-type. No implicit boxing conversion (§6.1.7) is ever performed for the expression of a lock statement, and thus it is a compile-time 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 bool __lockWasTaken = false; except that x is only evaluated once. While a mutual-exclusion lock is held, code executing in the same execution thread can also obtain and release the lock. However, code executing in other threads is blocked from obtaining the lock until the lock is released. Locking System.Type objects in order to synchronize access to static data is not recommended. Other code might lock on the same type, which can result in deadlock. A better approach is to synchronize access to static data by locking a private static object. For example: class Cache public static void Add(object x) { public static void Remove(object x) {
|