从异步函数获取当前方法名称? [英] Get current method name from async function?
问题描述
无论如何可以从异步函数内部获取当前方法名称?
Is there anyway to get the current method name from inside an async function?
我试过了:
System.Reflection.MethodInfo.GetCurrentMethod();
我尝试使用 StackTrace 和 StrackFrame 如下:
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());
}
但它们似乎都不起作用,我会得到.ctor"、InvokeMethod"、Invoke"、CreateInstance"、CreateKnownObject"或CreateUnknownObject"或MoveNext"
But neither of them seem to work, I'd get ".ctor", "InvokeMethod", "Invoke", "CreateInstance", "CreateKnownObject" or "CreateUnknownObject" or "MoveNext"
关于我如何做到这一点的任何想法?我想创建一个通用的logger函数,又不想传入调用logger函数的函数名,所以尝试了stacktrace方法,没用.
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.
我放弃了,说,好吧,我将函数名作为第一个参数传入,但是当我从调用通用记录器函数的调用函数调用反射方法时,我总是得到.ctor"
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...).
推荐答案
C# 5 添加了调用者信息属性,这可能会为您提供更多您正在寻找的信息.请注意,这些在编译时将适当的信息插入到调用站点中,而不是使用运行时信息.功能比较有限(显然你不能得到一个完整的调用堆栈),但速度要快得多.
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.
使用 CallerMemberNameAttribute 的示例:
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);
}
还有 CallerFilePath 和 CallerLineNumber 属性,它们可以获取有关呼叫站点的其他信息.
There are also CallerFilePath and CallerLineNumber attributes which can get other pieces of info about the call site.
这篇关于从异步函数获取当前方法名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!