I am looking to get the method/action name from a task in C#. Specifically I am implementing a custom task scheduler, and would like to generate statistics on the duration a task runs, which I will then aggregate by the method running inside of the task. In the visual studio debugger you can access this and see the m_action private variable, as well as the debugger display annotation, displays it as Method={0}. Is there any way to get access to this from the Task itself?
Well, you could use reflection to get at the private m_action
field, given a Task
variable task
:
var fieldInfo = typeof(Task).GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic);
Delegate action = fieldInfo.GetValue(task) as Delegate;
Then get the Name
of the method and the DeclaringType
:
var name = action.Method.Name;
var type = action.Method.DeclaringType.FullName;
To get the fully qualified method (type + "." + name
)...
But, as soon as the task executes to completion, m_action
is null
. I'm not sure how this would apply with TaskFactory.StartNew...