Get current method name from async function?

C# 5 added caller info attributes which may give you more what you are looking for. Note that these insert the appropriate information into the call site at compile-time rather than using run-time information. The functionality is more limited (you can’t get a complete call stack, obviously), but it is much faster.

An example using CallerMemberNameAttribute:

using System.Runtime.CompilerServices;

public static void Main(string[] args)
{
    Test().Wait();            
}

private static async Task Test()
{
    await Task.Yield();
    Log();
    await Task.Yield();
}

private static void Log([CallerMemberName]string name = "")
{
    Console.WriteLine("Log: {0}", name);
}

There are also CallerFilePath and CallerLineNumber attributes which can get other pieces of info about the call site.

Leave a Comment