How to Debug Multithreaded Program

In this post we will learn how to Debug Multithreaded Program. Let’s learn the followings:

  • How to work with multithreaded program debugging and see where your current thread is?
  • What is the execution sequence of thread?
  • What is the state of thread?

Before continuing with the actual process of threading, let’s consider you have the following piece of thread 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!");
}
}

Above you have 3 different threads: main thread, thread 1, thread 2. We have named the thread to make it easier for you to understand. Now set a breakpoint in “Go()” and run the application.

When the debugger reaches the breakpoint, press Ctrl+D, T or navigate through Debug > Window > Threads. A new thread window will appear to you on the screen.


Must Read :
11 Effective Debugging Tips for .NET Developer


What is the execution sequence of thread?

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

How to Debug Multithreaded Program

By default, the stream window has ID, Managed ID, Category, Name, Location, and Priority columns. At first, execution stops at “Main Thread”. The “yellow arrow” indicates the current execution flow. The Category column indicates the category of streams, such as main stream or job stream. If you check the thread location, it’s nothing but Namespace > Class > Method Name. In the diagram it shows that the main thread will be executed next. Now explore the next step by simply pressing “F5” and see what changes are in the string window.

How to Debug Multithreaded Program

What is the state of thread?

After pressing F5, it will go to the next step of thread 1. You can also check the current position of the main thread. It says “Sleep/Wait/Rejoin”, which means waiting for something to finish. Similarly, the next step will move you to thread 2. In the Thread window, you can understand how easy it is to monitor your threads with this debugging tool. There is another interesting feature available in the thread window. You can expand/collapse the string position and see what happens next. For example, if you expand the “Main Thread” location, it will look like the diagram below:

How to Debug Multithreaded Program

Above image expanded the location view for Threads.

I hope above will help. You can check more articles on our website under C# section HERE or you can also check same on Microsoft Docs too.

Leave a Reply

Your email address will not be published. Required fields are marked *