Can I add an attribute to a function to prevent reentry?

前端 未结 9 2542
梦谈多话
梦谈多话 2021-02-15 12:26

At the moment, I have some functions which look like this:

private bool inFunction1 = false;
public void function1()
{
    if (inFunction1) return;
    inFunctio         


        
9条回答
  •  天命终不由人
    2021-02-15 12:58

    You could build a PostSharp attribute to check to see if the name of the method is in the current stack trace

        [MethodImpl(MethodImplOptions.NoInlining)]
        private static bool IsReEntry() {
            StackTrace stack = new StackTrace();
            StackFrame[] frames = stack.GetFrames();
    
            if (frames.Length < 2)
                return false;
    
            string currentMethod = frames[1].GetMethod().Name;
    
            for (int i = 2; i < frames.Length; i++) {
                if (frames[i].GetMethod().Name == currentMethod) {
                    return true;
                }
            }
    
            return false;
        }
    

提交回复
热议问题