Get current method name from async function?

后端 未结 8 1274
我在风中等你
我在风中等你 2020-12-04 01:43

Is there anyway to get the current method name from inside an async function?

I\'ve tried:

System.Reflection.MethodInfo.GetCurrentMethod();
         


        
8条回答
  •  遥遥无期
    2020-12-04 02:13

    Rather than doing manual stack frame walks, which is both expensive and risky (since Release builds might optimize some methods out), you can use the CallerMemberNameAttribute, one of the Caller Information attributes, which was added in .NET 4.5 (which you already use, if you use async/await) for this exact scenario - passing in a member name for loggers, property-changed handlers and the like.

    It goes like this:

    public void LogMessage(string message, [CallerMemberName] string caller = "")
    { 
        // caller should contain the name of the method that called LogMessage.
    }
    

    I don't know of any limitation this has with async methods.

提交回复
热议问题