C# Interview Question #68

What is a race condition, and how can it be prevented?

Async/Await, Tasks & Multithreading Mid-Level Intermediate

Quick Interview Answer

A race condition occurs when multiple execution paths access shared mutable state concurrently and the program's result depends on timing or execution order.

Detailed Explanation

A race condition occurs when multiple execution paths access shared mutable state concurrently and the program's result depends on timing or execution order.

Race conditions can cause lost updates, corrupted state, and intermittent bugs that are difficult to reproduce.

They can be prevented or controlled using synchronization primitives such as lock, Monitor, SemaphoreSlim, Interlocked, immutable data, concurrent collections, or by designing the system to avoid shared mutable state.

Code Example

private readonly object _sync = new();
private int _count;

public void Increment()
{
    lock (_sync)
    {
        _count++;
    }
}