Thursday, July 19, 2012

Defending against the Dead[lock] with deadlock detection in the PostSharp Threading Toolkit

SharpCrafters Blog - Deadlock Detection using PostSharp Threading Toolkit

We’ve all experienced with great frustration that desktop applications can freeze: the user interface becomes irresponsive and, after a while, the message “Not Responding” is displayed in the title bar and the only escape is to kill the process. Typically, application freezes are the result of a deadlock where the foreground thread, instead of processing the message loop, waits for some resource to be released by a background thread, which in turn waits for the foreground thread to release some other resource.

Deadlocks Defined

A deadlock is a situation in which two or more competing actions are waiting for each other to finish, and thus neither ever does. Whenever you’re using locks there is a risk of deadlocks.

There are four main conditions necessary for a deadlock to occur:

a) A limited number of instances of a particular resource. In the case of a monitor in C# (what you use when you use the lock keyword), this limited number is one, since a monitor is a mutual-exclusion lock.

b) The ability to hold one resource and request another. In C#, this can be done by locking on one object and then locking on another before releasing the first lock, for example:


Detecting Deadlocks using the PostSharp Threading Toolkit

PostSharp Threading Toolkit features a drop-in deadlock detection policy. Without requiring any change in your code, it tracks use of thread synchronization primitives in transparent way. You can use locks, monitors, mutexes and most common primitives in the usual way and PostSharp Threading Toolkit will track all resources for you.

When a thread waits for a lock for more than 200ms, the toolkit will run a deadlock detection routine. If it detects a deadlock, it will throw DeadlockException in all threads that are part of the deadlock. The exception gives a detailed report of all threads and all locks involved in the deadlock, so you can analyze the issue and fix it.

In order to use deadlock detection mechanism, all you have to do is:

1. Add the PostSharp-Threading-Toolkit package to your project using NuGet.

2. Add the following line somewhere in your code (typically in AssemblyInfo.cs):



If you’ve ever experienced a deadlock in production, you know how hard it used to be to diagnose it. Not anymore. By adding the PostSharp-Threading-Toolkit NuGet package to your project and adding a single line of code to your code, you can get nice exception messages whenever a deadlock occurs.

In case you’re interested how this works under the hood, simply have a look at the source code in the Github repository (

Deadlocks can be a major pain to diagnose and troubleshoot, so I thought this a pretty cool toolkit. Then I saw that it was free and OSS! Now it's cool++...

No comments: