Pav*_*nin 7 .net c# reentrancy
我想禁止大量方法的重入.
单个方法适用于此代码:
bool _isInMyMethod;
void MyMethod()
{
if (_isInMethod)
throw new ReentrancyException();
_isInMethod = true;
try
{
...do something...
}
finally
{
_isInMethod = false;
}
}
Run Code Online (Sandbox Code Playgroud)
为每种方法做这件事都很繁琐.
所以我使用了StackTrace类:
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();
}
Run Code Online (Sandbox Code Playgroud)
它工作正常,但看起来更像一个黑客.
.NET Framework是否有特殊的API来检测重入?