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?
I recommend using PostSharp to solve your problem. Although it might be expensive to use commercial tool only for a specific reason I suggest you take a look since this tool can solve other problems better suited to be solved by AOP (logging, transaction management, security and more). The company web site is here and you can take a look on examples here. Pluralsight has a good course on the AOP methodology with examples in PostSharp here. Good luck!
The normal .Net approach is to use some for of synchronization to block other threads, rather than make them throw an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With