Follow @RoyOsherove on Twitter

TimedLock class: helping find and avoid deadlocks in your multithreaded code

Another gem I found through Eric's blog is the TimedLock class. It helps in locking and detecting the offending code in multi threading deadlock issues (at least makes it not as painful). Originally posted by IanG (and then republished), It was reintroduced and enhanced by Phill Haack (which looks to be the version you should be using to get a wonderful thing like a stack trace for a deadlocked thread...).
 
So - here's the recipe you should be following.. I think.
 
1.You should read the "why" on this class here
2. Then use the one found here 
3. But it's important that you fix the small bug in the class as is prescribed here! :).
 
"The TimedLock.Lock method can be called to lock an object. It returns an object that implements IDisposable. (As it happens, this is an instance of the TimedLock class, but it doesn't really matter what it is - a private nested class could also have been used.) Now we can write code like this:
using (TimedLock.Lock(obj)) { } 

This is a very similar usage model to using the lock keyword - we rely on a compiler-generated finally block to call Monitor.Exit. It's just a bit less direct - the generated block calls Dispose on the TimedLock, which in turn calls Monitor.Exit. But now, if the monitor cannot be acquired (e.g., because of a deadlock) the code will throw an exception after ten seconds instead of blocking for ever. We get pretty close to the succinctness of the lock keyword, but we get to use Monitor.TryEnter."

[Free eBook]FIT for Developing Software: Framework for Integrated Tests

Defensive event publishing, a different approach