Monitors

Monitors are used to provide thread-safe access to the resource. It is applicable to multithread programming, where there are multiple threads that need access to a resource simultaneously. When multiple threads attempt to enter monitor to access any resource, CLR allows only one thread at a time to enter and the other threads are blocked. When the thread exits the monitor, the next waiting thread enters, and so on.

If we look into the Monitor class, all the methods such as Monitor.Enter and Monitor.Exit operate on object references. Similarly to lock, Monitor also provides gated access to the resource; however, a developer will have greater control in terms of the API it provides.

Here is a basic example of using Monitor in .NET ...

Get Improving your C# Skills now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.