13.07.2015 Views

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>C#</strong> LANGUAGE SPECIFICATION15.12 The lock statementThe lock statement obtains the mutual-exclusion lock for a given object, executes a statement, and thenreleases the lock.lock-statement:lock ( expression ) embedded-statementThe 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 theexpression to denote a value of a value-type.A lock statement of the formlock (x) …where x is an expression of a reference-type, is precisely equivalent toSystem.Threading.Monitor.Enter(x);try {…}finally {System.Threading.Monitor.Exit(x);}except that x is only evaluated once.[Example: The System.Type object of a class can conveniently be used as the mutual-exclusion lock forstatic 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)) {…}}}end example]15.13 The using statementThe using statement obtains one or more resources, executes a statement, and then disposes of the resource.using-statement:using ( resource-acquisition ) embedded-statementresource-acquisition:local-variable-declarationexpressionA resource is a class or struct that implements System.IDisposable, which includes a singleparameterless method named Dispose. Code that is using a resource can call Dispose to indicate that theresource is no longer needed. If Dispose is not called, then automatic disposal eventually occurs as aconsequence of garbage collection.If the form of resource-acquisition is local-variable-declaration then the type of the local-variabledeclarationmust be System.IDisposable or a type that can be implicitly converted toSystem.IDisposable. If the form of resource-acquisition is expression then this expression must beSystem.IDisposable or a type that can be implicitly converted to System.IDisposable.198

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!