Be Careful with Locks
Just as with the
using statement, it’s highly recommended to keep the embedded block as tiny as possible. For both statements, the main motivation is contention. If a resource is used with the
using statement, others might be waiting for it, or you might be putting a needless amount of stress on the resource management system underneath. In case of a lock, you’ll be slowing down other threads, keeping them blocked longer than absolutely required to ensure the consistency we’re in search of.
But there’s another reason, too. Locking is just an essential primitive to provide for mutual exclusion between multiple threads of execution. But that’s about it. The
lock statement by itself doesn’t give any atomicity or consistency ...