Tuesday, October 6, 2015

.NET Monitor Locks are Re-Entrant

The purpose of the Monitor class in .NET (used by "SyncLock" in VB.NET and "lock" in C#) is to prevent different threads from entering a critical section at the same time. Care must be taken by the programmer to ensure that deadlocks - situations in which threads are waiting for each other directly or indirectly - are impossible. I recently needed to write a recursive function that happened to require careful threading, so I was concerned that the second invocation would hang waiting for the first to finish.

Fortunately, Monitor locks are re-entrant. If a section is entered for a given lock object on the same thread (e.g. in a recursive situation), the section will not be released until a matching amount of Exit calls are made. [Source: MSDN's article on Monitor.Enter]

No comments:

Post a Comment