Get current method name from async function?

后端 未结 8 1276
我在风中等你
我在风中等你 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.

    0 讨论(0)
  • 2020-12-04 02:14

    It's a bit late to answer your question I guess but since I had the same issue and I needed to figure it out on my own due to lack of a good resolution to this on the internet, here is what I did and it works perfectly at least for me -

    1. Define the following Regex somewhere that can be accessed by all callers since Regex objects need to be parsed before using them; hence, it can be expensive, and it's not a good practice to create them over and over if we can use the same one.
      public static readonly Regex ASYNC_METHOD_NAME_FORMAT = new Regex(@"^\<(?\w+)>\w+?");
    2. Use the following code to get the method name
      string methodName = ASYNC_METHOD_NAME_FORMAT.Match(MethodBase.GetCurrentMethod().ReflectedType.Name).Groups["method_name"].Value

    I hope this helps!

    0 讨论(0)
提交回复
热议问题