0

I'd like to get the running function's name every second. I tried with this code:

public static void DisplayTimeEvent(object source, ElapsedEventArgs e)
{
    // code here will run every second

    //Output is DisplayTimeEvent but I want it to print Main
    Console.WriteLine(GetCurrentMethod());
}

[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetCurrentMethod()
{
    StackTrace st = new StackTrace();
    StackFrame sf = st.GetFrame(1);

    return sf.GetMethod().Name;
}

//main function
Timer myTimer = new Timer();
myTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
myTimer.Interval = 1000;
myTimer.Start();
Console.ReadLine();

The code above prints DisplayTimeEvent. How can I make it print Main (or whatever function main thread is executing at that moment)?

derebaba
  • 28
  • 6
  • `sf.GetMethod().Name` should do that... – Rahul Feb 28 '18 at 07:51
  • Since `GetCurrentMethod` is called by `DisplayTimeEvent`, it returns `DisplayTimeEvent`. No matter what number I write in `st.GetFrame(1)`, it does not return Main. – derebaba Feb 28 '18 at 07:58
  • Why do you need this? Even if you did manage to capture it every second you will miss method calls in between. – Peter Bons Feb 28 '18 at 07:59
  • Can you point me in a direction where I can find the hard way? In my program, I am checking CPU usage every second using an event. I am creating a database log whenever CPU usage exceeds a certain threshold. I would like to add the current running function's name in my log. – derebaba Feb 28 '18 at 08:00

2 Answers2

0

Your thread prints DisplayTimeEvent because Timer.Elapsed event is attached to that callback and in your callback you only check stacktrace of current thread.

If you want to investigate other threads (including "Main thread") in your process, you can try with System.Diagnostics namespace as seen in this SO question.

Risto M
  • 2,919
  • 1
  • 14
  • 27
0

Yes, that's how it should be ... giving you the caller name of the method. Don't think you can get the current executing method like the way you are thinking. What if method calls are asynchronous or thread full operation ... how would that work?

FYI, one more option as of .NET 4.5 would be using CallerMemberNameAttribute

public static void DisplayTimeEvent(object source, ElapsedEventArgs e)
{
    Console.WriteLine("Test....");
    GetCurrentMethod();
}

public static string GetCurrentMethod([System.Runtime.CompilerServices.CallerMemberName] string memberName = "")
{
   System.Diagnostics.Trace.WriteLine("member name: " + memberName);
}
Rahul
  • 76,197
  • 13
  • 71
  • 125