Here is pattern I often use to perform locks:
private IDisposable GetLock()
{
_lock.Wait();
return new Disposable(()=> _lock.Release());
}
The only problem I see in this code is Thread.Abort(), it can enter in between _lock.Wait() and return statement, leaving lock in incosistent state. I tried to avoid this by saving it into variable:
private IDisposable GetLock()
{
var l = _lock;
l.Wait();
try
{
var result = new Disposable(()=> _lock.Release());
l = null; //<- I need to make this atomic, unabortable section
return result; //<- I need to make this atomic, unabortable section
}
finally
{
l?.Release();
}
}
But abortation will still deadlock this section sometime. How one could accomplish protection of this section against Thread.Abort()?