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)?

4
  • sf.GetMethod().Name should do that... Commented Feb 28, 2018 at 7: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. Commented Feb 28, 2018 at 7:58
  • Why do you need this? Even if you did manage to capture it every second you will miss method calls in between. Commented Feb 28, 2018 at 7: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. Commented Feb 28, 2018 at 8:00

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.