Debug Async Code

Introduction

 
There have always been problems implementing parallel tasks/threads. Even more questions arise when it is implemented and doesn't work as expected. It is hard to track or debug this type of code. However, using some methods or tools integrated with Visual Studio, we can debug the code and solve the issues. In this article, we are going to see how to debug async code.
 
We are going to use a sample async example from Microsoft and debug it. You can download it from here.
 
Pre-requisite knowledge to go through this article:
  1. All this is built into Visual Studio. Going through tools and analyzing data might be difficult if you have no prior experience in debugging. So, the first task is to understand what is async-await?. The second task is to learn basic debugging and then the third one is to debug through these tools. 
  2. To have knowledge of tasks and threads.

How to Debug?

 
We will be using below three tools/methods for our debugging purposes:
  1. Parallel Task
  2. Parallel Watch
  3. Tasks
All of the above windows can be opened in debug mode only. I have put the debug point at "return urlContents.Length;" in the sample code. Once it is hit, then we can open all three windows specified from "Debug->Windows". You can find them in the below screenshot.
 
Debug Async Code
 

Use of Parallel Task

 
Once the window is opened and code is in debug mode, we can see the stack trace of the code. There are two options in the window:
  1. Threads
    This shows all the current threads running with the stack trace of methods in it.


    Debug Async Code

  2. Tasks
    This shows all the current tasks running with task numbers. If we hover over the task it will show task number and other details which will be useful in parallel watch part.

    Debug Async Code

Use of Parallel Watch

 
There are four parallel watch windows. This helps in observing the same variable's value when multiple tasks are running simultaneously. We will be able to see the value changing task wise in the watch window. We can observe the stack trace from the parallel task window for task ID and then check the value in parallel watch window for that task.
 
Here, we will have one task and one value only based on our example. Below is the screenshot for parallel watch window:
 
Debug Async Code
 

Use of Tasks

 
One question arises here, what is the difference between the parallel task window and the task window? The difference here is that the parallel task window is a visual representation of tasks and in the tasks window, we can see the state of the task as well. If a task is in deadlock/active/awaiting/any other state, then it will be visible here. Below is a screenshot.
 
Debug Async Code
 

Summary

 
Async code can be analyzed through a parallel task, parallel watch, parallel threads, or the tasks window. Use all these tools together to analyze async code thoroughly.


Similar Articles