How much work should I place inside a lock statement?

Technology CommunityCategory: ConcurrencyHow much work should I place inside a lock statement?
VietMX Staff asked 3 years ago

It is first and foremost a question of correctness. You should not care so much about efficiency trade-offs, but more about correctness.

  • Do as little work as possible while locking a particular object. Locks that are held for a long time are subject to contention, and contention is slow. Note that this implies that the total amount of code in a particular lock and the total amount of code in all lock statements that lock on the same object are both relevant.
  • Have as few locks as possible, to make the likelihood of deadlocks (or livelocks) lower.
  • If you want concurrency, use processes as your unit of concurrency. If you cannot use processes then use application domains. If you cannot use application domains, then have your threads managed by the Task Parallel Library and write your code in terms of high-level tasks (jobs) rather than low-level threads (workers).
  • Benchmarking and being aware that there are more options than “lock everything everywhere” and “lock only the bare minimum”.