C# Interview Question #69

What is the lock keyword in C#?

Async/Await, Tasks & Multithreading Mid-Level Intermediate

Quick Interview Answer

The lock statement provides mutual exclusion around a critical section. Only one thread can execute code protected by the same lock object at a time.

Detailed Explanation

The lock statement provides mutual exclusion around a critical section. Only one thread can execute code protected by the same lock object at a time.

It is useful for protecting shared in-process mutable state. The protected region should normally be kept small to reduce contention.

A common rule is not to await asynchronous work while holding a traditional lock. For asynchronous coordination, SemaphoreSlim is often more appropriate.

Code Example

private readonly object _sync = new();

public void Update()
{
    lock (_sync)
    {
        // Access shared state safely.
    }
}