C# Interview Question #114

What is deadlock, and how can it be avoided?

Concurrency, Performance & Design Senior Advanced

Quick Interview Answer

A deadlock occurs when operations wait indefinitely for resources or each other in a cycle, so none can continue.

Detailed Explanation

A deadlock occurs when operations wait indefinitely for resources or each other in a cycle, so none can continue.

In multithreaded code, deadlocks can occur when locks are acquired in inconsistent orders. In asynchronous code, blocking on asynchronous tasks with .Result or .Wait can also create deadlock risks in environments with synchronization contexts, in addition to causing thread starvation.

Common prevention techniques include consistent lock ordering, keeping critical sections small, avoiding unnecessary nested locks, using async all the way, and applying cancellation or timeouts where appropriate.