Troubleshootng Deadlocks in .NET Applications

What do you do when your application become unresponsive due to potential deadlocks?

I think the first thing to do is to identify exactly where the application hangs due to a deadlock. To do this you should replace the lock(…) statement with it’s equivalent Monitor.Enter(…)/Monitor.Exit(…). Monitor has an argument which alloys you to specify timeout. So when you change the suspicious code with Monitor.Enter(…)/Monitor.Exit(…) while specifying the timeout, the code will throw the exception when this timeout has exceeded the specified timeout. While this doesn’t solve the dead lock issue, it points you to the location within you code where there is a possible issue.

Additionally, you need to make sure that the locks are taken in the same order i.e,

lock(_a)
{
     lock(_b)
    {
        ....
    } 
}

This is only for troubleshooting purposes. You should revert back to normal locking when the issue is found and fixed.

One easy thing you can do is to pause execution within Visual Studio by pressing on the pause button and then see what each thread is up to.

You also might want to consider more granular locking primitives, such ReadWriterLockerSlim and refactor you code to use less locking.

Whenever you feel like putting a lock always question yourself if this is the right thing to do and if there is a way doing this without locking all together

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: