Monitor Class

[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]

Provides a mechanism that synchronizes access to objects.

System..::..Object
  System.Threading..::..Monitor

Namespace:  System.Threading
Assembly:  mscorlib (in mscorlib.dll)

'Declaration
Public NotInheritable Class Monitor

The Monitor type exposes the following members.

  NameDescription
Public methodStatic memberEnterAcquires an exclusive lock on the specified object.
Public methodStatic memberExitReleases an exclusive lock on the specified object.
Top

The Monitor class controls access to objects by granting a lock for an object to a single thread. Object locks provide the ability to restrict access to a block of code, commonly called a critical section. While a thread owns the lock for an object, no other thread can acquire that lock. You can also use Monitor to ensure that no other thread is allowed to access a section of application code being executed by the lock owner, unless the other thread is executing the code using a different locked object.

NoteNote

Use Monitor to lock objects (that is, reference types), not value types. For details, see the Enter method.

Monitor has the following features:

  • It is associated with an object on demand.

  • It is unbound, which means it can be called directly from any context.

  • An instance of the Monitor class cannot be created.

The following information is maintained for each synchronized object:

  • A reference to the thread that currently holds the lock.

  • A reference to a ready queue, which contains the threads that are ready to obtain the lock.

  • A reference to a waiting queue, which contains the threads that are waiting for notification of a change in the state of the locked object.

Use the Enter and Exit methods to mark the beginning and end of a critical section. If the critical section is a set of contiguous instructions, then the lock acquired by the Enter method guarantees that only a single thread can execute the enclosed code with the locked object. In this case, it is recommended you place those instructions in a try block and place the Exit instruction in a finally block. This facility is typically used to synchronize access to a static or instance method of a class. The functionality provided by the Enter and Exit methods is identical to that provided by the C# lock statement (SyncLock in Visual Basic), except that lock and SyncLock wrap the Enter(Object, Boolean%) method overload and the Exit method in a tryfinally block (TryFinally in Visual Basic) to ensure that the monitor is released.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show: