Suppose I have the following code:
public class SomeClass()
{
private readonly object _lock = new object();
public void SomeMethodA()
{
lock
But there does not appear to be such a method. Monitor.TryEnter does not help because locks are re-entrant. Therefore, if the current thread already owns the lock, TryEnter will still succeed and return true. The only time it will fail is if another thread owns the lock and the call times out.
I found a workaround that works similar to Monitor.TryEnter() and yet doesn't have the re-entrant issues. Basically instead of using Monitor.TryEnter(), you can use Monitor.Pulse(). This function throws a SynchronizationLockException exception if the current thread doesn't hold the lock.
example:
try
{
System.Threading.Monitor.Pulse(lockObj);
}
catch (System.Threading.SynchronizationLockException /*ex*/)
{
// This lock is unlocked! run and hide ;)
}
Docs: http://msdn.microsoft.com/en-us/library/system.threading.monitor.pulse.aspx