C# and .NET • Modern C# baseline
Tasks, Locks, and Thread-Safe State
Coordinate concurrent access with synchronization or avoid shared mutable state.
Tasks represent units of asynchronous or scheduled work, but multiple tasks can still access shared data concurrently. A lock protects a critical section; concurrent collections provide purpose-built operations. Avoid holding locks across await because the lock may block unrelated work and cannot be safely held across suspension.
Key points
- Prefer immutable data or message passing when practical.
- Use Interlocked for simple atomic operations when its semantics fit.
Example
private readonly object _gate = new();
private int _completed;
public void MarkCompleted()
{
lock (_gate)
{
_completed++;
}
}
What to expect
Concurrent calls update _completed within a protected critical section.
Practice exercise
Add a read method and ensure it uses the same synchronization strategy.
Key idea: Thread safety is a property of the whole invariant, not just one field.