1

How do I get the name of the method I am executing given the following signature:

MyMethodAsync( ()=> myservice.GetCustomer)

public async Task MyMethodAsync(Func<Task> taskToExecute)
{
    //Get the name of the task that is executing 
    //   eg "myservice.GetCustomer

    taskToExecute.??
}


public async Task MyMethodAsync<T>(Func<Task<T>> taskToExecute)
{
    //Get the name of the task that is executing eg 
    // "myservice.GetCustomer

}

Desired result: myservice.GetCustomer

I have tried as follows, but it does not work. Ideally I'd like to do it without reflection

string methodName = taskToExecute.GetMethodInfo().Name;
BanksySan
  • 27,362
  • 33
  • 117
  • 216
developer9969
  • 4,628
  • 6
  • 40
  • 88
  • 1
    Keep in mind what lambdas do. Your code is roughly equivalent to `MyMethodAsync(CompilerGeneratedMethod); Task CompilerGeneratedMethod() { return myservice.GetCustomer; }`. Hoping to extract `myservice.GetCustomer` from that is going to be very difficult. Do you really need to stick with that exact signature? –  Jul 29 '17 at 09:51
  • I would like to log the method that is invoked ideally that is the main purpose. What is the best I can get? – developer9969 Jul 29 '17 at 09:53
  • Here you [go](https://stackoverflow.com/a/2652481) bud – boop_the_snoot Jul 29 '17 at 10:08
  • @Nobody hi I forgot to mention the most important thing is a portable class library. I cannot seem to have Stacktrace – developer9969 Jul 29 '17 at 10:36
  • 1
    if that is so check [this post](https://stackoverflow.com/questions/23593496/equivalent-for-system-diagnostics-trace-in-pcl-library) and [this solution](https://stackoverflow.com/a/28015917/6611487). – boop_the_snoot Jul 29 '17 at 10:42
  • 1
    Could you go Expression based? Don't know if that's available in PCL. With a little work you'd be able to get the method names but then you'd have to compile and invoke the lambda manually. You'd never be able to get the variable name (myservice) though - - just the method name. It also wouldn't work well (or at all?) if your lambdas were complex (multi statement). – pinkfloydx33 Jul 29 '17 at 11:19

0 Answers0