I am looking at code that has been created and it uses a TryEnter in one method call and lock in others. So, like this:
private readonly object xmppLock = new object();
void f1()
{
if (Monitor.TryEnter(xmppLock))
{
try
{
// Do stuff
}
finally
{
Monitor.Exit(xmppLock);
}
}
}
void f2()
{
lock(xmppLock)
{
// Do stuff
}
}
Is this okay?
lock
is just syntax sugar for Monitor.Enter
, so yes, it will work fine.
The Visual Basic SyncLock and C# lock statements use Monitor.Enter to take the lock and Monitor.Exit to release it. The advantage of using the language statements is that everything in the lock or SyncLock block is included in a Try statement.
(That said, it's considered poor form to lock on something public like a Type
object.)
Yes these two constructs will work together. The C# lock
keyword is just a thin wrapper over the Monitor.Enter
and Monitor.TryEnter
methods.
Note: I would absolutely avoid using a Type
instance as the value to lock on. Doing so is very fragile as it makes it very easy for two completely unrelated pieces of code to be unexpectedly locking on the same object. This can lead to deadlocks.
lock will block until the resource is available
TryEnter will not do anything if it is already locked.
Depending on your needs you have to use one or the other.
In your case f2()
will always do what ever it does no matter how long it takes. f1()
will return immediately if there is lock contention
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With