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

前端 未结 9 2385
梦谈多话
梦谈多话 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:55

    Without assembly and IL rewriting, there's no way for you to create a custom attribute that modifies the code in the way you describe.

    I suggest that you use a delegate-based approach instead, e.g. for functions of a single argument:

    static Func WrapAgainstReentry(Func code, Func onReentry)
    {
        bool entered = false;
        return x =>
        {
            if (entered)
                return onReentry(x);
            entered = true;
            try
            {
                return code(x);
            }
            finally
            {
                entered = false;
            }
        };
    }
    

    This method takes the function to wrap (assuming it matches Func - you can write other variants, or a totally generic version with more effort) and an alternate function to call in cases of reentry. (The alternate function could throw an exception, or return immediately, etc.) Then, throughout your code where you would normally be calling the passed method, you call the delegate returned by WrapAgainstReentry() instead.

提交回复
热议问题