Consider this code:
lock(myGuard)
{
// do some stuff that is being synchronized
}
the C# compiler generates the following code for you
Monitor.Enter(myGuard);
try
{
// do some stuff that is being synchronized
}
finally
{
Monitor.Exit(myGuard);
}
So lock is an exception proof (and short) way of acquiring a monitor and making sure it gets freed again.
but, if u use Monitor, the code blow is better.
if (!Monitor.TryEnter(obj, TimeSpan.FromSeconds(10))
{
throw new ApplicationException("Timeout waiting for lock");
}
try
{
... do something with shared state ...
}
finally
{
Monitor.Exit(obj);
}
A Mutex can be shared across processes, and is much more heavy-weight than a Monitor.
Use a Monitor unless you need to synchronize across process boundaries.
if u want to learn more, u can check