Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug only one thread in Visual Studio [duplicate]

I would like to be able to follow only one thread's execution while debugging. I use a threadpool so the debugger keeps switching between threads and this makes debugging very uncomfortable.

Reading:

  • Visual Studio, debug one of multiple threads
  • How to debug a single thread in Visual Studio?

I get one solution which is conditional breakpoints (based on the name of the thread). However, I can't tell "the thread #3" will always be the one treating the interesting case, so I would have to change the condition for each execution. Too much work.

Another solution is to use the freeze/thaw feature to make only my interesting thread run. However, this make some information unavailable because all threads are paused.

What I am using now is to put make the program run until I get to a breakpoint where I am sure to be in the good thread. Then I pause all other threads of threadpool and try to resume the execution. If the programs seems to be stuck, I pause, and thaw the current thread.

The ideal solution would to find the correct thread, flag it and then say to Visual Studio: "break only if the current thread is flagged".

Is this even possible ?

like image 566
kamaradclimber Avatar asked Nov 18 '11 14:11

kamaradclimber


People also ask

Why it is difficult to debug multi threaded programs?

Multithreaded applications are always harder to debug as you have to track multiple threads at a time. Moreover, multithreaded applications introduce new types of bugs and performance issues like uneven workload distribution, lock contention, serialized execution, and other*.


3 Answers

While debugging you can freeze all the threads in the Threads window and resume only the one you're interested in.

like image 171
Bode Avatar answered Nov 14 '22 13:11

Bode


I would use the conditional breakpoints you mentioned, but instead of comparing to some fixed string compare to some semi-global variable (maybe a static property on your main class?).

When you identify which thread becomes interesting you can use the immediate window to set the variable name and allow your conditional breakpoints to be hit.

like image 32
MBirchmeier Avatar answered Nov 14 '22 14:11

MBirchmeier


A bit late but this cropped up as the first answer in a search.

I use the following in VS 2015...

var thread = System.Threading.Thread.CurrentThread;
if (thread.Name == null)
            thread.Name = "Main";

Then in the breakpoint...

System.Threading.Thread.CurrentThread.Name == "Main"

To make it more flexible you can embed Thread in a custom class.

FYI: You cannot use static variables in a conditional breakpoint as they are not in context. Never really understood why statics are not always in context.

like image 2
Paulustrious Avatar answered Nov 14 '22 13:11

Paulustrious