When we want a thread-centric view of our application, the Threads window is the place to start. We can use the Threads window to see the location of all of our threads, see the thread call stack, and more. We can use the Call Stack window to view the stack frames of our application, or the function, or procedure calls that are currently on the stack.
In this recipe, we are going to see how to use the Threads and Call Stack windows in Visual Studio 2012 to view the call stack information for the threads in our application.
Before we start looking at the debugging features of Visual Studio 2012, we need an application to debug. Let's create a Console
application that spins up a few tasks so we can take a look at their call stack information.
LockExample
as the Solution name.using
directives to the top of your Program
class.using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks;
static
methods on the Program
class. Add a method named Method1
that loops three times, creating tasks. The tasks just need to call Method2
with an integer
parameter.static void Method1() { Console.WriteLine("In Method1."); for (int i = 0; i < 3; i++) { Task.Factory.StartNew(index => Method2((int)index), i); } }
Method2
. Method2
just adds a random number to the parameter, writes the parameter to Console
, and calls Method4
.static void Method2(int number) { Random rnd = new Random(); var sum = number + rnd.Next(1,10); Console.WriteLine("In Method2. Value:{0}", sum); Method4(sum); }
Method3
, which just starts a third task that calls Method2
.static void Method3() { Console.WriteLine("In Method3."); for (int i = 0; i < 3; i++) { Task.Factory.StartNew(() => { Task.Factory.StartNew(index => Method2((int)index), i); }); Thread.Sleep(10); } }
Method4
which contains our breakpoint.static void Method4(int number) { Console.WriteLine("In Method4.", number); Debugger.Break(); }
Main
method, create a task that calls Method1
and Task
that calls Method3
. Wait for the user input before exiting.static void Main() { var task1 = Task.Factory.StartNew(() => Method1()); var task2 = Task.Factory.StartNew(() => Method3()); Console.ReadLine(); }
Let's start a debugging session and take a look at the window.
Debug.Break
statement, go to the Debug menu of Visual Studio 2012, and click on Windows, and click on Call Stack to view the Threads window.3.21.93.245