Did you know that Visual Studio shows deadlocked tasks?

I didn’t…
And it’s not a new feature – since it existed since freaking Visual Studio 2010!
Yesterday during an unrelated meeting Alon Fliess showed a bunch of us developers how Visual Studio detects deadlocks in tasks (automatically) and shows the current task status in both Parallel Tasks and Tasks debug windows (duh).
I got home late but I wanted to experiment and see what would happen and so I wrote a simple program to see how well Visual Studio understands the bugs I can trough at it:
static void Main(string[] args) 
{ 
    int taskCount = 6; 
    var tasks = new Task[taskCount]; 
    var autoResetEvent = new AutoResetEvent(false); 
    for (int i = 0; i < taskCount; i++) 
    { 
        tasks[i] = Task.Factory.StartNew(state => 
        { 
            var index = (int)state; 
            if (index < 3) 
            { 
                tasks[(index + 1) % 3].Wait(); 
            } 
            else if (index == 3) 
            { 
                Task.Factory.StartNew(() => 
                { 
                    while (true) { } 
                }).Wait(); 
            } 
            else 
            { 
                autoResetEvent.WaitOne(); 
            } 
        }, i); 
    } 

    Task.WaitAll(tasks); 

    autoResetEvent.Set(); 
}
What a mess – I have three tasks waiting on each other (deadlocked), two more tasks waiting indefinitely on a AutoResetEvent and one task that starts yet another task that runs an infinite loop (just for fun).
After a few seconds I paused/breaked execution and got the following (Debug –> windows –> Tasks):
image
So out of the 6 tasks I spawned the first three deadlocks are detected by VS, Three tasks that show as blocked (waiting for AutoResetEvent and waiting for another task to complete). The only task that shows as running is the one that happily burning CPU on a while loop that would never end (also known as the Halting problem).
That’s good enough for me.
I guess it’s another case of a useful feature that I always wanted but didn’t know already existed.

Happy coding…

Labels: , , ,