Get current method name from async function?

后端 未结 8 1280
我在风中等你
我在风中等你 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: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!

提交回复
热议问题