Monitor
ClassThe System.Threading.Monitor
class is the support object for the SyncLock..End SyncLock
statement, and the compiler translates SyncLock
blocks into invocations to the Monitor
class. You use it as follows:
Monitor.Enter
now has an overload that takes a second argument of type Boolean
, passed by reference, indicating if the lock was taken. This is new in .NET Framework 4.0.
Basically Monitor.Enter
locks the object whereas Monitor.Exit
unlocks it. It is fundamental to place Monitor.Exit
in the Finally
part of the Try..Catch
block so that resources will be unlocked anyway. At this point you might wonder why use Monitor
instead of SyncLock..End SyncLock
because they produce the same result. The difference is that Monitor also exposes additional members, such as the TryEnter
method that supports timeout, as demonstrated here:
Monitor.TryEnter(lockObject, 3000, result)
This code attempts to obtain the lock on the specified object for three seconds before terminating.
3.138.123.190