请问 .NET Core 中如何知道一个 Task 所对应的方法名称?
比如下面的 C# 代码:
class Program
{
static void Main(string[] args)
{
var task = RequestCnblogsQ();
}
private static async Task RequestCnblogsQ()
{
await new HttpClient().GetAsync("https://q.cnblogs.com/");
}
}
如何通过 task 知道其对应的方法名称 RequestCnblogsQ ?
通过回答中的方法,反射拿到的 m_action
值总是 null
var task = RequestCnblogsQ();
var fieldInfo = typeof(Task).GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic);
var action = fieldInfo.GetValue(task);
@dudu: 一旦 Task 运行完毕,m_action
就是 null
了,可以改成这样:
Task t = new Task<Task>(DoSomething);
var fieldInfo = typeof(Task).GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic);
Delegate action = fieldInfo.GetValue(t) as Delegate;
Console.WriteLine(action.Method.Name);
t.Start();
@沈星繁: t.Start()
会抛异常:
Unhandled Exception: System.InvalidOperationException: Start may not be called on a task that hascompleted.
at System.Threading.Tasks.Task.Start(TaskScheduler scheduler)
@dudu:
先把 Task new 出来(此时没有运行里面的方法),取方法名(可能是用来写 Log 的?),再运行 Task。
我的测试代码是这样的,运行是没有问题的:
using System;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var task = new Task<Task>(RequestCnblogsQ);
var fieldInfo = typeof(Task).GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic);
Delegate action = fieldInfo.GetValue(task) as Delegate;
Console.WriteLine(action.Method.Name);
task.Start();
}
private static async Task RequestCnblogsQ()
{
await new HttpClient().GetAsync("https://q.cnblogs.com/");
}
}
}
@沈星繁: 赞!的确可以
没有办法,找到办法了告诉我一下。。。。
见最佳答案