Async Deadlocks
Question
Can tasks cause a deadlock? How can you avoid it?
Short interview answer
Yes. A common deadlock occurs when code blocks on
Task.ResultorWait()while the awaited continuation needs the blocked synchronization context. Preferawaitall the way through the call chain.
Detailed answer
In a UI context, a synchronous wait can block the UI thread while an awaited continuation tries to resume there. Avoid mixing synchronous blocking with asynchronous code. Use await, avoid unnecessary context dependencies in library code, and keep async operations from blocking threads that they need to resume.
For example, a UI thread that calls LoadAsync().Result can block itself while LoadAsync is waiting to resume on that same UI context. Replacing the blocking call with await LoadAsync() leaves the context free to resume the operation.