.NET

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 throw 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):

Fig1_6150

So out of the 6 tasks I spawned the first three deadlocks are detected by VS, Three tasks that show as blocked (waiting for AutoResetEventand 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…

Related Articles

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button