Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid deadlock in .NET

Is there are any common practices or rules to avoid deadlock in a program? Also is there any support from CLR or any instrument from language/framework to Handle such scenario?

like image 445
user854301 Avatar asked Mar 08 '26 14:03

user854301


1 Answers

Note that little of this is .net-specific:

The biggest way of avoiding a deadlock is to lock in a consistent order; this means you get regular blocking rather than a deadlock, but requires much thought and planning about what you are locking and when. Of course, this thought and planning is necessary anyway.

One simple way of achieving this is: try to only need one lock object at a time; so instead of locking A and B, you lock (separately) A then B. This too requires thought and planning, but is usually achievable.

Taking it more generally, avoiding over-granular locks can be a huge sanity-saver here. For lock objects that could compete, put serious consideration into just using a single lock of for both concepts. In many cases this doesn't hugely impact the time spent competing, but makes the code much simpler and more reliable.

Actually, one gripe I do have with the language is that "take a lock but with a timeout" is so much more code-intensive than "take a lock". Ensuring you always have timeouts can also ensure that a total lockup becomes recoverable. But this should mainly just be used to identify areas that are locking in the wrong order, so that you can fix them.

like image 200
Marc Gravell Avatar answered Mar 11 '26 02:03

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!