ECMA-334 C# Language Specification15.12: The lock statement |
The lock statement obtains the mutual-exclusion lock for a given object, executes a statement, and then releases the lock.
(
expression
)
embedded-statement
The expression of a lock statement must denote a value of a reference-type
. No implicit boxing conversion (13.1.5) 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) ... |
reference-type
, is precisely equivalent to System.Threading.Monitor.Enter(x); try { ... } finally { System.Threading.Monitor.Exit(x); } |
end example]
class Cache
{
public static void Add(object x) {
lock (typeof(Cache)) {
...
}
}
public static void Remove(object x) {
lock (typeof(Cache)) {
...
}
}
}