Debugging multithreaded and asynchronous code
Let’s join the league of super debuggers. We are about to embark on a journey into the depths of multithreaded systems and where they go wrong.
Multithreaded code is notoriously hard to debug. Imagine you have two threads that interact with each other, and then things go wrong. However, if you step through the methods in Visual Studio, things work just fine, and that makes sense: some bugs appear only when certain timing conditions happen.
Parallel Watch
What about this: you have multiple threads, and something goes wrong. You want to inspect what happens in that thread. But if you set a breakpoint, how do you know you are in the correct thread?
Fear not: Visual Studio can help with this. Let’s start with the following code:
var rnd = new Random(); for (int i = 0; i < 10; i++) { int threadNumber = i; ThreadPool.QueueUserWorkItem(_ => ...