获得异步函数当前方法的名字吗? [英] Get current method name from async function?

查看:98
本文介绍了获得异步函数当前方法的名字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

反正从一个异步函数中获取当前方法的名字吗?

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

我试过:

System.Reflection.MethodInfo.GetCurrentMethod();

和我使用堆栈跟踪和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,调用,的CreateInstance,CreateKnownObject或CreateUnknownObject或MoveNext的

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.

我放弃了上说,好吧,我会在函数名传递作为第一个参数,但是当我打电话从调用通用记录器功能的调用函数的反射法,我总是得到.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆