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,
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