Debugging Multithreaded Program

By | August 21, 2013

This post talks about; how to work with multithreaded program debugging, where is your current thread, what is the thread execution sequence, what is the state of thread. Before continuing with the actual process, let’s consider you have the following piece of code which you want to debug.

class ThreadTest
{
static void Main()
{
Thread t = new Thread(new ThreadStart(Go));
t.Name = "Thread 1";
Thread t1 = new Thread(new ThreadStart(Go));
t1.Name = "Thread 2";
t.Start();
t1.Start();
Go();
}
static void Go()
{
Console.WriteLine("hello!");
}
}

In the above , you have three different threads – Main Thread, Thread 1, Thread 2. I have given a thread name to make you understand better. Now set a breakpoint inside “Go()” and run the application. When debugger hits the breakpoint, Press Ctrl+D,T or Navigate through Debug > Window > Threads. Threads window will appeared on the screen.

After selecting the thread window from debug menu, the following screen will come:

Multithreaded debugging

By default thread window having ID, Managed ID, Category, Name, Location and Priority column. At the start, execution pauses at “Main Thread”. “Yellow Arrow” indicates the current executable thread. Category column indicates the category of threads, like main thread or worker thread. If you check the thread location, it is nothing but Namespace > Class > Method name. In the diagram, it is showing that the Main Thread will be executed next. Now to explore the next step by just pressing “F5” and see what are the changes in thread window.

Multithreaded debugging

So after pressing F5, it jumped to the next step to thread 1. you can also check the current location for Main Thread. It says “Sleep/ Wait / Join” , means waiting for something to complete. Similarly the next step will move you to thread 2. From the Thread window, you can understand how easy it is to monitor your threads using this debugger tool.

There is another great feature available within the thread window. You can expand/collapse the Thread Location and can see what is next. For example, if you expand the location for “Main Thread”, it will look like the diagram given below:

Multithreaded debugging

Figure: Expanded Location View For Threads

I have taken this part of the post from one of my article on “Mastering Debugging in Visual Studio 2010 – A Beginner’s Guide, from Code Project”. You can refer to that post for more fundamentals and internals of debugging.

2 thoughts on “Debugging Multithreaded Program

  1. Pingback: .NET Tips and Tricks from Daily .NET Tips – July and August 2013 Links | Abhijit's World of .NET

  2. Pingback: 10 Effective Debugging Tips for .NET Developer

Comments are closed.