[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]
Acquires an exclusive lock on the specified object.
Assembly: mscorlib (in mscorlib.dll)
Use Enter to acquire the Monitor on the object passed as the parameter. If another thread has executed an Enter on the object but has not yet executed the corresponding Exit, the current thread will block until the other thread releases the object. It is legal for the same thread to invoke Enter more than once without it blocking; however, an equal number of Exit calls must be invoked before other threads waiting on the object will unblock.
Use Monitor to lock objects (that is, reference types), not value types. When you pass a value type variable to Enter, it is boxed as an object. If you pass the same variable to Enter again, it is boxed as a separate object, and the thread does not block. In this case, the code that Monitor is supposedly protecting is not protected. Furthermore, when you pass the variable to Exit, still another separate object is created. Because the object passed to Exit is different from the object passed to Enter, Monitor throws .
can interrupt threads that are waiting to enter a Monitor on an object. A will be thrown.
Use a C# try…finally block (Try…Finally in Visual Basic) to ensure that you release the monitor, or use the C# lock statement (SyncLock statement in Visual Basic), which wraps the and Exit methods in a try…finally block.
- Full trust for the immediate caller. This member cannot be used by partially trusted code. For more information, see dd66cd4c-b087-415f-9c3e-94e3a1835f74.