Does framework have dedicated api to detect reentrancy?

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!


正常的.Net方法是使用一些同步来阻塞其他线程,而不是让它们抛出异常。

链接地址: http://www.djcxy.com/p/67200.html

上一篇: 删除contenteditable中所有选中的HTML标签

下一篇: 框架是否有专门的api来检测重入?