Introduction
Sometimes you have a need to break in certain part of code only when a particular thread is running that code. This tip will describe how to do that using Visual Studio Breakpoint Filter.
Consider the following code. The code itself is very trivial but is good enough to explain the idea.
class Program
{
private static object sync = new object();
static void Main(string[] args)
{
for(int i = 0; i < 10; i++)
{
Thread t = new Thread(new ThreadStart(Test));
t.Name = "Thread" + i.ToString();
t.Start();
Thread.Sleep(10);
}
Console.ReadKey();
}
static void Test()
{
lock (sync)
{
Console.WriteLine("Thread name = {0}, Id = {1} is processing now",
Thread.CurrentThread.Name,Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(5 * 1000);
}
}
}
In the Main
method, we launch 10 threads. Each of the threads will be running the same method called Test
. The important thing to notice is that we have used Name
property of Thread
instance because this is what we will use to filter the breakpoint. Now let's say we need to break in Test
method only when this method is executed by thread named Thread3
. For this, we will first set a breakpoint on the line in Test
Method that is calling Console.WriteLine
just by hitting F9. Now if you right click on that break point symbol (red circle), you will get a context menu as shown below:
Selecting Filter option from this context menu will bring "Breakpoint Filter" dialog as shown below:
As the name of this dialog suggests, you can use it to filter the break point for a particular process/thread. As you can see in the figure above, I am using a filter for thread name Thread3
. Once you hit OK here, a + sign will appear in the red circle indicating that break point has more information as shown below:
Now if you run the code, this break point will hit only when Thread3
is running the method. Of course, you can verify that break point filter is correctly being called by inspecting related data.
One question that may arise is what if you are not naming your threads in the code as we have done in the sample for this tip. The good thing is that even though you may not have set Name
property of your thread in code, you can still give your thread a name from Threads windows. For doing that, first bring up Threads window using Debug->Windows->Thread menu option. At this point, if you right click on a thread in this windows, you will get the following context menu. One of the options in this context menu is Rename as shown in the figure below:
If you select this option, you can simply type the name of this thread inline in the same window as shown below:
Once this is done, you can go back to Breakpoint Filter dialog and adjust your filter for the newly renamed thread.