Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.
Traducción
Inglés

Clase Monitor

 

Proporciona un mecanismo que sincroniza el acceso a los objetos.

Espacio de nombres:   System.Threading
Ensamblado:  mscorlib (en mscorlib.dll)

System::Object
  System.Threading::Monitor

[ComVisibleAttribute(true)]
[HostProtectionAttribute(SecurityAction::LinkDemand, Synchronization = true, 
	ExternalThreading = true)]
public ref class Monitor abstract sealed 

NombreDescripción
System_CAPS_pubmethodSystem_CAPS_staticEnter(Object^)

Adquiere un bloqueo exclusivo en el objeto especificado.

System_CAPS_pubmethodSystem_CAPS_staticEnter(Object^, Boolean%)

Adquiere un bloqueo exclusivo en el objeto especificado y establece de forma atómica un valor que indica si se realizó el bloqueo.

System_CAPS_pubmethodSystem_CAPS_staticExit(Object^)

Libera un bloqueo exclusivo en el objeto especificado.

System_CAPS_pubmethodSystem_CAPS_staticIsEntered(Object^)

Determina si el subproceso actual mantiene el bloqueo en el objeto especificado.

System_CAPS_pubmethodSystem_CAPS_staticPulse(Object^)

Notifica un cambio de estado del objeto bloqueado al subproceso que se encuentra en la cola de espera.

System_CAPS_pubmethodSystem_CAPS_staticPulseAll(Object^)

Notifica un cambio de estado del objeto a todos los subprocesos que se encuentran en espera.

System_CAPS_pubmethodSystem_CAPS_staticTryEnter(Object^)

Intenta adquirir un bloqueo exclusivo en el objeto especificado.

System_CAPS_pubmethodSystem_CAPS_staticTryEnter(Object^, Boolean%)

Intenta adquirir un bloqueo exclusivo en el objeto especificado y establece de forma atómica un valor que indica si se realizó el bloqueo.

System_CAPS_pubmethodSystem_CAPS_staticTryEnter(Object^, Int32)

Intenta adquirir un bloqueo exclusivo en el objeto especificado durante el número de segundos especificado.

System_CAPS_pubmethodSystem_CAPS_staticTryEnter(Object^, Int32, Boolean%)

Intenta, durante el número especificado de milisegundos, adquirir un bloqueo exclusivo en el objeto especificado y establece de forma atómica un valor que indica si se realizó el bloqueo.

System_CAPS_pubmethodSystem_CAPS_staticTryEnter(Object^, TimeSpan)

Intenta adquirir un bloqueo exclusivo en el objeto especificado durante el período de tiempo especificado.

System_CAPS_pubmethodSystem_CAPS_staticTryEnter(Object^, TimeSpan, Boolean%)

Intenta, durante el periodo de tiempo indicado, adquirir un bloqueo exclusivo en el objeto especificado y establece de forma atómica un valor que indica si se realizó el bloqueo.

System_CAPS_pubmethodSystem_CAPS_staticWait(Object^)

Libera el bloqueo en un objeto y bloquea el subproceso actual hasta que vuelve a adquirir el bloqueo.

System_CAPS_pubmethodSystem_CAPS_staticWait(Object^, Int32)

Libera el bloqueo en un objeto y bloquea el subproceso actual hasta que vuelve a adquirir el bloqueo. Si transcurre el intervalo de tiempo de espera especificado, el subproceso entra en la cola de subprocesos listos.

System_CAPS_pubmethodSystem_CAPS_staticWait(Object^, Int32, Boolean)

Libera el bloqueo en un objeto y bloquea el subproceso actual hasta que vuelve a adquirir el bloqueo. Si transcurre el intervalo de tiempo de espera especificado, el subproceso entra en la cola de subprocesos listos. Este método también especifica si el dominio de sincronización del contexto (si se trata de un contexto sincronizado) sale antes de la espera y vuelve a adquirir el bloqueo después.

System_CAPS_pubmethodSystem_CAPS_staticWait(Object^, TimeSpan)

Libera el bloqueo en un objeto y bloquea el subproceso actual hasta que vuelve a adquirir el bloqueo. Si transcurre el intervalo de tiempo de espera especificado, el subproceso entra en la cola de subprocesos listos.

System_CAPS_pubmethodSystem_CAPS_staticWait(Object^, TimeSpan, Boolean)

Libera el bloqueo en un objeto y bloquea el subproceso actual hasta que vuelve a adquirir el bloqueo. Si transcurre el intervalo de tiempo de espera especificado, el subproceso entra en la cola de subprocesos listos. De modo opcional, sale del dominio de sincronización del contexto sincronizado antes de la espera y vuelve a adquirir el dominio después.

The T:System.Threading.Monitor class allows you to synchronize access to a region of code by taking and releasing a lock on a particular object by calling the M:System.Threading.Monitor.Enter(System.Object), M:System.Threading.Monitor.TryEnter(System.Object), and M:System.Threading.Monitor.Exit(System.Object) methods. 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 the T:System.Threading.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.

In this article:

The Monitor class: An overview
The lock object
The critical section
Pulse, PulseAll, and Wait
Monitors and wait handles

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 T:System.Threading.Monitor class cannot be created; the methods of the T:System.Threading.Monitor class are all static. Each method is passed the synchronized object that controls access to the critical section.

System_CAPS_noteNota

Use the T:System.Threading.Monitor class to lock objects other than strings (that is, reference types other than T:System.String), not value types. For details, see the overloads of the M:System.Threading.Monitor.Enter(System.Object) method and The lock object section later in this article.

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.

Beginning with the net_v40_long, there are two sets of overloads for the Overload:System.Threading.Monitor.Enter and Overload:System.Threading.Monitor.TryEnter methods. One set of overloads has a ref (in C#) or ByRef (in Visual Basic) T:System.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. 

The Monitor class consists of static (in C#) or Shared (in Visual Basic) methods that operate on an object that controls access to the critical section. 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.

Monitor locks objects (that is, reference types), not value types. While you can pass a value type to Enter and Exit, it is boxed separately for each call. Since each call creates a separate object, Enter never blocks, and the code it is supposedly protecting is not really synchronized. In addition, the object passed to Exit is different from the object passed to Enter, so Monitor throws SynchronizationLockException exception with the message "Object synchronization method was called from an unsynchronized block of code."

The following example illustrates this problem. It launches ten tasks, each of which just sleeps for 250 milliseconds. Each task then updates a counter variable, nTasks, which is intended to count the number of tasks that actually launched and executed. Because nTasks is a global variable that can be updated by multiple tasks simultaneously, a monitor is used to protect it from simultaneous modification by multiple tasks. However, as the output from the example shows, each of the tasks throws a T:System.Threading.SynchronizationLockException exception.

No hay ningún ejemplo de código disponible o este idioma no es compatible.

Each task throws a T:System.Threading.SynchronizationLockException exception because the nTasks variable is boxed before the call to the M:System.Threading.Monitor.Enter(System.Object) method in each task. In other words, each method call is passed a separate variable that is independent of the others. nTasks is boxed again in the call to the M:System.Threading.Monitor.Exit(System.Object) method. Once again, this creates ten new boxed variables, which are independent of each other, nTasks, and the ten boxed variables created in the call to the M:System.Threading.Monitor.Enter(System.Object) method. The exception is thrown, then, because our code is attempting to release a lock on a newly created variable that was not previously locked.

Although you can box a value type variable before calling M:System.Threading.Monitor.Enter(System.Object) and M:System.Threading.Monitor.Exit(System.Object), as shown in the following example, and pass the same boxed object to both methods, there is no advantage to doing this. Changes to the unboxed variable are not reflected in the boxed copy, and there is no way to change the value of the boxed copy.

No hay ningún ejemplo de código disponible o este idioma no es compatible.

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.

Note that you can synchronize on an object in multiple application domains if the object used for the lock derives from T:System.MarshalByRefObject.

Use the M:System.Threading.Monitor.Enter(System.Object) and M:System.Threading.Monitor.Exit(System.Object) methods to mark the beginning and end of a critical section.

System_CAPS_noteNota

The functionality provided by the M:System.Threading.Monitor.Enter(System.Object) and M:System.Threading.Monitor.Exit(System.Object) methods is identical to that provided by the lock statement in C# and the SyncLock statement in Visual Basic, except that the language constructs wrap the M:System.Threading.Monitor.Enter(System.Object,System.Boolean@) method overload and the M:System.Threading.Monitor.Exit(System.Object) method in a try…finally block to ensure that the monitor is released.

If the critical section is a set of contiguous instructions, then the lock acquired by the M:System.Threading.Monitor.Enter(System.Object) method guarantees that only a single thread can execute the enclosed code with the locked object. In this case, we recommend that you place that code in a try block and place the call to the M:System.Threading.Monitor.Exit(System.Object) method in a finally block. This ensures that the lock is released even if an exception occurs. The following code fragment illustrates this pattern.

No hay ningún ejemplo de código disponible o este idioma no es compatible.

This facility is typically used to synchronize access to a static or instance method of a class.

If a critical section spans an entire method, the locking facility can be achieved by placing the T:System.Runtime.CompilerServices.MethodImplAttribute on the method, and specifying the F:System.Runtime.CompilerServices.MethodImplOptions.Synchronized value in the constructor of T:System.Runtime.CompilerServices.MethodImplAttribute. When you use this attribute, the M:System.Threading.Monitor.Enter(System.Object) and M:System.Threading.Monitor.Exit(System.Object) method calls are not needed. The following code fragment illustrates this pattern:

No hay ningún ejemplo de código disponible o este idioma no es compatible.

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 T:System.Threading.Monitor class, the C# lock statement, or the Visual Basic SyncLock statement inside of the method instead of the attribute.

While it is possible for the M:System.Threading.Monitor.Enter(System.Object) and M:System.Threading.Monitor.Exit(System.Object) statements that lock and release a given object to cross member or class boundaries or both, this practice is not recommended.

Once a thread owns the lock and has entered the critical section that the lock protects, it can call the M:System.Threading.Monitor.Wait(System.Object), M:System.Threading.Monitor.Pulse(System.Object), and M:System.Threading.Monitor.PulseAll(System.Object) methods.

Wait releases the lock if it is held, allows a waiting thread or threads to obtain the lock and enter the critical section, and waits to be notified by a call to the Monitor::Pulse or Monitor::PulseAll method. When Wait is notified, it returns and obtains the lock again.

Both M:System.Threading.Monitor.Pulse(System.Object) and M:System.Threading.Monitor.PulseAll(System.Object) signal for the next thread in the wait queue to proceed.

It is important to note the distinction between the use of the T:System.Threading.Monitor class and T:System.Threading.WaitHandle objects.

  • The T:System.Threading.Monitor class is purely managed, fully portable, and might be more efficient in terms of operating-system resource requirements.

  • WaitHandle objects represent operating-system waitable objects, are useful for synchronizing between managed and unmanaged code, and expose some advanced operating-system features like the ability to wait on many objects at once.

The following example uses the T:System.Threading.Monitor class to synchronize access to a single instance of a random number generator represented by the T:System.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 hay ningún ejemplo de código disponible o este idioma no es compatible.

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 M:System.Threading.Interlocked.Add(System.Int64@,System.Int64) method is used for this purpose.

The following example demonstrates the combined use of the T:System.Threading.Monitor class (implemented with the lock or SyncLock language construct), the T:System.Threading.Interlocked class, and the T:System.Threading.AutoResetEvent class. It defines two internal (in C#) or Friend (in Visual Basic) classes, SyncResource and UnSyncResource, that respectively provide synchronized and unsynchronized access to a resource. To ensure that the example illustrates the difference between the synchronized and unsynchronized access (which could be the case if each method call completes rapidly), the method includes a random delay: for threads whose P:System.Threading.Thread.ManagedThreadId property is even, the method calls M:System.Threading.Thread.Sleep(System.Int32) to introduce a delay of 2,000 milliseconds. Note that, because the SyncResource class is not public, none of the client code takes a lock on the synchronized resource; the internal class itself takes the lock. This prevents malicious code from taking a lock on a public object.

No hay ningún ejemplo de código disponible o este idioma no es compatible.

The example defines a variable, numOps, that defines the number of threads that will attempt to access the resource. The application thread calls the M:System.Threading.ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback) method for synchronized and unsynchronized access five times each. The M:System.Threading.ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback) method has a single parameter, a delegate that accepts no parameters and returns no value. For synchronized access, it invokes the SyncUpdateResource method; for unsynchronized access, it invokes the UnSyncUpdateResource method. After each set of method calls, the application thread calls the AutoResetEvent.WaitOnehttps://msdn.microsoft.com/library/58195swd.aspx method so that it blocks until the T:System.Threading.AutoResetEvent instance is signaled.

Each call to the SyncUpdateResource method calls the internal SyncResource.Access method and then calls the M:System.Threading.Interlocked.Decrement(System.Int64@) method to decrement the numOps counter. The M:System.Threading.Interlocked.Decrement(System.Int64@) method Is used to decrement the counter, because otherwise you cannot be certain that a second thread will access the value before a first thread's decremented value has been stored in the variable. When the last synchronized worker thread decrements the counter to zero, indicating that all synchronized threads have completed accessing the resource, the SyncUpdateResource method calls the EventWaitHandle.Sethttps://msdn.microsoft.com/library/system.threading.eventwaithandle.set.aspx method, which signals the main thread to continue execution.

Each call to the UnSyncUpdateResource method calls the internal UnSyncResource.Access method and then calls the M:System.Threading.Interlocked.Decrement(System.Int64@) method to decrement the numOps counter. Once again, the M:System.Threading.Interlocked.Decrement(System.Int64@) method Is used to decrement the counter to ensure that a second thread does not access the value before a first thread's decremented value has been assigned to the variable. When the last unsynchronized worker thread decrements the counter to zero, indicating that no more unsynchronized threads need to access the resource, the UnSyncUpdateResource method calls the EventWaitHandle.Sethttps://msdn.microsoft.com/library/system.threading.eventwaithandle.set.aspx method, which signals the main thread to continue execution.

As the output from the example shows, synchronized access ensures that the calling thread exits the protected resource before another thread can access it; each thread waits on its predecessor. On the other hand, without the lock, the UnSyncResource.Access method is called in the order in which threads reach it.

Plataforma universal de Windows
Disponible desde 8
.NET Framework
Disponible desde 1.1
Biblioteca de clases portable
Se admite en: plataformas portátiles de .NET
Silverlight
Disponible desde 2.0
Windows Phone Silverlight
Disponible desde 7.0
Windows Phone
Disponible desde 8.1

This type is thread safe.

Volver al principio
Mostrar: