Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Getting Visual Studio to Display Deadlocked Tasks

DZone's Guide to

Getting Visual Studio to Display Deadlocked Tasks

Visual Studio, since version 2010, can show tasks which are deadlocked. So, I wrote a basic program to reveal these tasks. Enjoy!

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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, 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(); 
}

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 awhile 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…

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:
it analytics ,visual studio ,web dev

Published at DZone with permission of Dror Helper, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}