我想禁止大量方法的重入。
对于单一方法,此代码有效:
bool _isInMyMethod;
void MyMethod()
{
if (_isInMethod)
throw new ReentrancyException();
_isInMethod = true;
try
{
...do something...
}
finally
{
_isInMethod = false;
}
}
对每个方法都这样做很乏味。
所以我使用了 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();
}
它工作正常,但看起来更像是 hack。
.NET Framework 是否有特殊的 API 来检测重入?
最佳答案
我建议使用 PostSharp 来解决您的问题。尽管仅出于特定原因使用商业工具可能会很昂贵,但我建议您看一下,因为该工具可以解决更适合由 AOP 解决的其他问题(日志记录、事务管理、安全性等)。公司网址为here你可以看看例子here . Pluralsight 在 PostSharp 中有一个很好的 AOP 方法论类(class)和示例 here .祝你好运!
关于c# - 框架是否有专门的 api 来检测重入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13881433/