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.
Ensamblado: mscorlib (en mscorlib.dll)
|TryEnter(Object^, Int32, Boolean%)|
|TryEnter(Object^, TimeSpan, Boolean%)|
|Wait(Object^, Int32, Boolean)|
|Wait(Object^, TimeSpan, Boolean)|
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:
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.
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:
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.
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.
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.
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.
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 throws SynchronizationLockException exception with the message "Object synchronization method was called from an unsynchronized block of code."locks objects (that is, reference types), not value types. While you can pass a value type to
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.
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.
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.
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.
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:
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.
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.
Disponible desde 8
Disponible desde 1.1
Biblioteca de clases portable
Se admite en: plataformas portátiles de .NET
Disponible desde 2.0
Windows Phone Silverlight
Disponible desde 7.0
Disponible desde 8.1
This type is thread safe.