I want to prohibit reentrancy for large set of methods.
for the single method works this code:
bool _isInMyMethod;
void MyMethod()
{
if (_isInMethod)
throw new ReentrancyException();
_isInMethod = true;
try
{
...do something...
}
finally
{
_isInMethod = false;
}
}
This is tedious to do it for every method.
So I've used StackTrace class:
public static void ThrowIfReentrant()
{
var stackTrace = new StackTrace(false);
var frames = stackTrace.GetFrames();
var callingMethod = frames[1].GetMethod();
if (frames.Skip(2).Any( frame => EqualityComparer<MethodBase>.Default.Equals(callingMethod,frame.GetMethod())))
throw new ReentrancyException();
}
It works fine but looks more like a hack.
Does .NET Framework have special API to detect reentrancy?