框架是否有专门的api来检测重入?

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来检测重入?

Ika*_*aso 3

我建议使用 PostSharp 来解决您的问题。虽然仅出于特定原因使用商业工具可能会很昂贵,但我建议您看一下,因为该工具可以解决其他更适合 AOP 解决的问题(日志记录、事务管理、安全性等)。该公司的网站在这里,您可以在这里查看示例。Pluralsight 有一个关于 AOP 方法的很好的课程,其中有 PostSharp 中的示例。祝你好运!