Using  & Lock Statements   


Obtaining the resources, executing it and disposing them off is done by the using statement. A resource is a class or struct that implements System.IDisposable. This resource includes a single parameterless method named Dispose( ). Code that is using the resource can call Dispose( ) to indicate that the resource is no longer needed. If Dispose( ) is not called, then automatic disposal eventually occurs as a consequence of garbage collection.

The using statement is translated into 3 parts: acquisition, usage, and disposal. Usage of the resource is enclosed in a try statement that includes a finally clause. This finally clause disposes of the resource. If a null resource is acquired, then no call to Dispose( ) is made, and no exception is thrown.

using ( test t = new test ( ) )
{

t.func( ) ;

}

 

is precisely equivalent to

 

test t = new test ( ) ;
try
{

t. func ( ) ;

}

finally
{

if ( t != null )

(( IDisposable ) t ). Dispose ( ) ;

}

Similarly two consecutive using statements are equivalent to nested try-finally blocks.


Lock Statement

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

The lock statement of the form

lock ( x )

is equivalent to

System.Threading.Monitor.Exit( x ) ;
try
{

code

}

finally
{

System.Threading.Monitor.Exit ( x ) ;

}

except that x is only evaluated once. The exact behaviour of the Enter and Exit methods of the System.Threading.Monitor class is implementation-defined.