4

In C# multi-threaded programming, when method A() calls method B() in a new thread, e.g. by using something like this:

Task A()
{
    // ...

    // I want B to run in parallel, without A() waiting for it.
    Task.Factory.StartNew(B); 
}

void B()
{
     // I attach a debugger here to look at the Call Stack.
     // But that is empty and I can't see that A() actually called it (logically).

     // Also Environment.StackTrace is pretty much empty of that path.
}

In other words inside method B() the stack trace doesn't know anything about the call path to method A() which in turn triggered execute of method B().

Is there any way to see the full logical stack trace, so e.g. in the case of an exception in B() you can see the full story to know A() in effect called it?

VMAtm
  • 27,943
  • 17
  • 79
  • 125
Paymon
  • 1,173
  • 1
  • 9
  • 26
  • @SimonPrice, that's how to debug multi-threaded programs in general. OP is looking for a way to find out which thread (and call stack to that point) started another thread / scheduled a task, should that task throw an exception. Got anything more specific? – Roger Lipscombe Jan 28 '17 at 10:50
  • I have updated the question with more details. You can easily create this scenario in Visual Studio to see for yourself. – Paymon Jan 28 '17 at 10:59
  • I'm testing this in a UWP application, if that helps. – Paymon Jan 28 '17 at 11:04
  • 2
    This information isn't captured. A new thread is a new starting point. Best you can get is to give your threads a useful name. – jessehouwing Jan 28 '17 at 12:52

1 Answers1

1

In general the answer is No, as StackTrace by definition cannot contain information from other stack. However, if you debugging your application in Visual studio, it do some work for you (this is C++, but it's similar for all the languages):

enter image description here

Here, external code is dimmer than your, and you can review some "parent" thread information. However, usually this screen isn't much helpful. Visual studio creates vshost.exe file for gather as much debug information as possible.

Also, if you create the task withh attaching them to parent, and there is some exception, you'll get full stacktrace with exception's ToString method, but still it's not exactly what you want.

Community
  • 1
  • 1
VMAtm
  • 27,943
  • 17
  • 79
  • 125
  • 1
    I ended up creating my own SynchronizationContext to keep track of nested thread calls. – Paymon Jan 28 '17 at 14:06
  • @Paymon can you explain more in detail what you ended up with? –  Jan 16 '18 at 14:27
  • It's a bit too complex to explain. I pretty much engineered a whole API around multi-threading in our framework to make it work. I doubt you want to go there. – Paymon Jan 17 '18 at 14:56