Reputation: 3733
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?
Upvotes: 7
Views: 5659
Reputation: 754715
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.
Upvotes: 7
Reputation: 71935
lock
is just syntax sugar for Monitor.Enter
, so yes, it will work fine.
(That said, it's considered poor form to lock on something public like a Type
object.)
Upvotes: 11
Reputation: 24403
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
Upvotes: 2