X hits on this document





198 / 396

Chapter ‎18   Unsafe code

The checked and unchecked statements are precisely equivalent to the checked and unchecked operators (§‎7.5.12), except that they operate on blocks instead of expressions.

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. No implicit boxing conversion (§‎6.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) ...

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

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

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.

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)) { ... } } }

8.13 The using statement

The using statement obtains one or more resources, executes a statement, and then disposes of the resource.

using-statement: using   (    resource-acquisition   )    embedded-statement

Copyright Microsoft Corporation 1999-2003. All Rights Reserved.185

Document info
Document views1271
Page views1271
Page last viewedFri Jan 20 12:50:28 UTC 2017