Back to Writing
NOTEScsharpthreadinglockconcurrencythread-safety
C# Lock Statement — Thread Safety Guide
November 29, 2019•Updated Feb 17, 2026
The lock statement in C# is used to ensure thread safety.
Syntax:
lock(obj) {
// Critical section
}
The lock statement guarantees that only one thread at a time can execute the critical section.
Example:
private object lockObj = new object();
private int count = 0;
public void Increment() {
lock(lockObj) {
count++;
}
}
Key Points:
- The lock statement uses a SyncLock mechanism
- The object used for locking must not be null
- Keep critical sections short to prevent deadlocks
Alternative (C# 8.0+):
private readonly object lockObj = new object();
public void Increment() {
lock(lockObj) {
count++;
}
}