Reputation: 5493
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?
Upvotes: 3
Views: 13832
Reputation: 1062745
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.
Upvotes: 12
Reputation: 334
I think the best you to go around your problem is to use the normal process of control. Guard access to your resources using Mutexes or Semaphores.
This might help you
http://msdn.microsoft.com/en-us/library/hw29w7t1(v=vs.71).aspx
Upvotes: 1
Reputation: 245419
MSDN actually has several good articles on this topic, one of which being:
Avoiding and Detecting Deadlocks in .NET Apps with C# and C++
Upvotes: 8