Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

c# - Get current method name from async function?

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

I've tried:

System.Reflection.MethodInfo.GetCurrentMethod();

And I've tried using StackTrace and StrackFrame as follows:

StackTrace strackTrace = new StackTrace();

for (int i = 0; i < strackTrace.GetFrames().Length; i++)
{
    SafeNativeMethods.EtwTraceInfo("Function" + i + ":" + function);
    SafeNativeMethods.EtwTraceInfo("Type" + i + ":" + strackTrace.GetFrame(i).GetType().Name);
    SafeNativeMethods.EtwTraceInfo("Method" + i + ":" + strackTrace.GetFrame(i).GetMethod().Name);
    SafeNativeMethods.EtwTraceInfo("ToString Call" + i + ":" + strackTrace.GetFrame(i).ToString());
}

But neither of them seem to work, I'd get ".ctor", "InvokeMethod", "Invoke", "CreateInstance", "CreateKnownObject" or "CreateUnknownObject" or "MoveNext"

Any ideas on how I can do this? I want to create a generic logger function and I don't want to pass in the name of the function that called the logger function, so I tried the stacktrace method, didn't work.

I gave up on that and said, ok, I'll pass in the function name as the first parameter, but when I called the reflection method from the calling function that calls the generic logger function, I always get ".ctor"

Any ideas? Note the generic logger function I'm calling is a static method in the same class (it has to be this way for now...).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...