How can I get stack trace of a currently executing

2019-08-14 04:54发布

问题:

I have a method that is called every time a new event to the application arrives. This method spins up a new task to process the event so we can return quickly. For example:

public void HandleEvent(Event e)
{
  Task.Run(() => 
  {
    // Do something with e
  }
}

Sometimes processing that event takes a really long time and I want to find out why. One way I am thinking of doing this is to keep track of all currently executing such tasks and create a monitoring thread that keeps an eye for any tasks that have taken longer than a certain amount of time. When that happens, have the monitor take a stack trace of that task's thread.

Is this possible?

I suppose that if it's impossible or too difficult to get a stack trace of a running thread that I could somehow trigger ProcDump externally, though that would be overkill and potentially grab a lot of data I don't need. (This is a server process so I expect that there will be hundreds if not thousands of processing threads).

Thanks in advance,

Dan