Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 496
Pavel Voronin Avatar asked Dec 14 '12 15:12

Pavel Voronin


2 Answers

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!

like image 156
Ikaso Avatar answered Nov 08 '22 13:11

Ikaso


The normal .Net approach is to use some for of synchronization to block other threads, rather than make them throw an exception.

like image 1
Jodrell Avatar answered Nov 08 '22 11:11

Jodrell