Export (0) Print
Expand All

Monitor Class

Provides a mechanism that synchronizes access to objects.

System.Object
  System.Threading.Monitor

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

[<AbstractClass>]
[<Sealed>]
type Monitor =  class end

The Monitor type exposes the following members.

  NameDescription
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryEnter(Object)Acquires an exclusive lock on the specified object.
Public methodStatic memberSupported by Portable Class LibraryEnter(Object, Boolean)Acquires an exclusive lock on the specified object, and atomically sets a value that indicates whether the lock was taken.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryExitReleases an exclusive lock on the specified object.
Public methodStatic memberIsEnteredDetermines whether the current thread holds the lock on the specified object.
Public methodStatic memberSupported by Portable Class LibraryPulseNotifies a thread in the waiting queue of a change in the locked object's state.
Public methodStatic memberSupported by Portable Class LibraryPulseAllNotifies all waiting threads of a change in the object's state.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryTryEnter(Object)Attempts to acquire an exclusive lock on the specified object.
Public methodStatic memberSupported by Portable Class LibraryTryEnter(Object, Boolean)Attempts to acquire an exclusive lock on the specified object, and atomically sets a value that indicates whether the lock was taken.
Public methodStatic memberSupported by Portable Class LibraryTryEnter(Object, Int32)Attempts, for the specified number of milliseconds, to acquire an exclusive lock on the specified object.
Public methodStatic memberSupported by Portable Class LibraryTryEnter(Object, TimeSpan)Attempts, for the specified amount of time, to acquire an exclusive lock on the specified object.
Public methodStatic memberSupported by Portable Class LibraryTryEnter(Object, Int32, Boolean)Attempts, for the specified number of milliseconds, to acquire an exclusive lock on the specified object, and atomically sets a value that indicates whether the lock was taken.
Public methodStatic memberSupported by Portable Class LibraryTryEnter(Object, TimeSpan, Boolean)Attempts, for the specified amount of time, to acquire an exclusive lock on the specified object, and atomically sets a value that indicates whether the lock was taken.
Public methodStatic memberSupported by Portable Class LibraryWait(Object)Releases the lock on an object and blocks the current thread until it reacquires the lock.
Public methodStatic memberSupported by Portable Class LibraryWait(Object, Int32)Releases the lock on an object and blocks the current thread until it reacquires the lock. If the specified time-out interval elapses, the thread enters the ready queue.
Public methodStatic memberSupported by Portable Class LibraryWait(Object, TimeSpan)Releases the lock on an object and blocks the current thread until it reacquires the lock. If the specified time-out interval elapses, the thread enters the ready queue.
Public methodStatic memberWait(Object, Int32, Boolean)Releases the lock on an object and blocks the current thread until it reacquires the lock. If the specified time-out interval elapses, the thread enters the ready queue. This method also specifies whether the synchronization domain for the context (if in a synchronized context) is exited before the wait and reacquired afterward.
Public methodStatic memberWait(Object, TimeSpan, Boolean)Releases the lock on an object and blocks the current thread until it reacquires the lock. If the specified time-out interval elapses, the thread enters the ready queue. Optionally exits the synchronization domain for the synchronized context before the wait and reacquires the domain afterward.
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 class 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 other than strings (that is, reference types other than String), not value types. For details, see the overloads of the Enter method and the Monitors conceptual topic.

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.

The following table describes the actions that can be taken by threads that access synchronized objects:

Action

Description

Enter, TryEnter

Acquires a lock for an object. This action also marks the beginning of a critical section. No other thread can enter the critical section unless it is executing the instructions in the critical section using a different locked object.

Wait

Releases the lock on an object in order to permit other threads to lock and access the object. The calling thread waits while another thread accesses the object. Pulse signals are used to notify waiting threads about changes to an object's state.

Pulse (signal), PulseAll

Sends a signal to one or more waiting threads. The signal notifies a waiting thread that the state of the locked object has changed, and the owner of the lock is ready to release the lock. The waiting thread is placed in the object's ready queue so that it might eventually receive the lock for the object. Once the thread has the lock, it can check the new state of the object to see if the required state has been reached.

Exit

Releases the lock on an object. This action also marks the end of a critical section protected by 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.

Beginning with the .NET Framework 4, there are two sets of overloads for the Enter and TryEnter methods. One set of overloads has a ref (ByRef in Visual Basic) Boolean parameter that is atomically set to true if the lock is acquired, even if an exception is thrown when acquiring the lock. Use these overloads if it is critical to release the lock in all cases, even when the resources the lock is protecting might not be in a consistent state. 

If a critical section spans an entire method, the locking facility described above can be achieved by placing the System.Runtime.CompilerServices.MethodImplAttribute on the method, and specifying the Synchronized value in the constructor of MethodImplAttribute. Using this attribute, the Enter and Exit statements are not needed. Note that the attribute causes the current thread to hold the lock until the method returns; if the lock can be released sooner, use the Monitor class, the C# lock statement, or the Visual Basic SyncLock statement instead of the attribute.

While it is possible for the Enter and Exit statements that lock and release a given object to cross member or class boundaries or both, this practice is not recommended.

When selecting an object on which to synchronize, you should lock only on private or internal objects. Locking on external objects might result in deadlocks, because unrelated code could choose the same objects to lock on for different purposes.

The following example uses the Monitor class to synchronize access to a single instance of a random number generator represented by the Random class. The example creates ten tasks, each of which executes asynchronously on a thread pool thread. Each task generates 10,000 random numbers, calculates their average, and updates two procedure-level variables that maintain a running total of the number of random numbers generated and their sum. After all tasks have executed, these two values are then used to calculate the overall mean.

No code example is currently available or this language may not be supported.

Because they can be accessed from any task running on a thread pool thread, access to the variables total and n must also be synchronized. The Interlocked.Add method is used for this purpose.

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0

Portable Class Library

Supported in: Portable Class Library

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8

This type is thread safe.

Show:
© 2015 Microsoft