C# EXPERTChapter 6 · C# Expert
Thread safety and lock synchronization
The Task Parallel Library (TPL) executes tasks concurrently. When threads modify shared state, use the lock statement to restrict critical region access to one thread at a time.
Worked example
using System;
using System.Threading.Tasks;
class Program {
static readonly object _lock = new object();
static int _count = 0;
static void Main() {
Parallel.For(0, 100, i => {
lock (_lock) {
_count++;
}
});
Console.WriteLine(_count);
}
}How it reads
- lock (_lock) ensures only one thread enters the body block at a time
- Parallel.For executes actions in parallel using multiple threads

Cloud tip: Only lock reference types (usually a private dedicated object), never lock value types or strings.


