Show/Hide Toolbars

XSharp

Purpose

The BEGIN LOCK and END LOCK keywords mark a block of statements as a critical section.

Syntax

BEGIN LOCK object
  statements
END LOCK

Arguments

 

object An expression that evaluates to an object reference that is used as a locking object.
statements One or more statements or expressions that are guarded by a mutual exclusion lock on the object specified in object.

Remarks

 

BEGIN LOCK ... END LOCK insures that multiple threads cannot execute the statements within the block at the same time. If one thread is executing code within the block, any other thread that attempts to enter the block will be suspended until the thread that is executing leaves the block.

The object used as the locking object must be a reference type, it cannot be a value type and the expression cannot evaluate to NULL or a runtime error will occur.

BEGIN LOCK ... END LOCK uses Monitor.Enter() and Monitor.Exit() to acquire and release a lock on the specified object. The following example:

 

BEGIN LOCK lockObj
? "In guarded block"
END LOCK

is equivalent to:

System.Threading.Monitor.Enter( lockObj )
TRY
? "In guarded block"
FINALLY
System.Threading.Monitor.Exit( lockObj )
END TRY

 

 

Using BEGIN LOCK ... END LOCK is recommended over using the Monitor class directly because the code is more concise and insures that the monitor object is released even if an exception occurs within the guarded block.

BEGIN LOCK ... END LOCK provides functionality similar to the Windows API functions EnterCriticalSection() and LeaveCriticalSection(). However, instead of using an object created by InitializeCriticalSection(), any instance of a reference type may be used for the locking object.

Please see the documentation for the System.Threading.Monitor class for more information.