In my unsafe class below, what can be done to prevent someone from executing the unsafe method without first obtaining the lock?
class Unsafe
{
private static readonly object lockObj;
void MethodA()
{
lock (lockObj)
{
// do some things
DoUnsafeThing();
}
}
void MethodB()
{
lock (lockObj)
{
// do some things
DoUnsafeThing();
}
}
void DoUnsafeThing()
{
if (callerHasLock)
// Do the unsafe thing
else
return; // or throw some exception
}
}
Obtaining the lock again inside DoUnsafeThing()
is an option:
void DoUnsafeThing()
{
lock (lockObj)
{
// Do the unsafe thing
}
}
But DoUnsafeThing()
can now be called by threads that don't already possess the lock.