Suppose I have the following code:
public class SomeClass()
{
private readonly object _lock = new object();
public void SomeMethodA()
{
lock
I had similiar requirements of checking whether a lock is locked by the current thread, so I can do something like this.
public void Method1()
{
if(!lockHeld()) lock();
//DO something
}
public void Method2()
{
if(!lockHeld()) lock();
//DO something
}
public void Method3()
{
if(!lockHeld()) lock();
//Do something
unlock()
}
So I wrote myself a class for that:
public class LockObject
{
private Object internalLock;
private bool isLocked;
public bool IsLocked
{
get { lock (internalLock) return isLocked; }
private set { lock (internalLock) isLocked = value; }
}
public LockObject()
{
internalLock = new object();
}
public void UsingLock(Action method)
{
try
{
Monitor.Enter(this);
this.IsLocked = true;
method();
}
finally
{
this.IsLocked = false;
Monitor.Exit(this);
}
}
}
Then I can use it as:
public void Example()
{
var obj = new LockObject();
obj.UsingLock(() =>
{
//Locked, and obj.IsLocked = true
});
}
Note: I ommitted the Lock() Unlock() Methods on this class, but pretty much just wrappers to Monitor.Enter/Exit that set IsLocked to true. The example just illustrates that its very similar to lock(){ } in terms on style.
Might be unnecessary, but this is useful for me.