lock, Mutex, Semaphore - synchronisation in C#
This ties directly into the thread-safety topic we discussed with Singletons - all three mechanisms serve to control access by many threads to a shared resource, but they differ in scope, semantics and cost.
lock - the simplest, within one process
lock is syntactic sugar over Monitor.Enter/Monitor.Exit - it ensures that only one thread at a time can execute a given block of code.
public class CounterService
{
private readonly object _lockObject = new object();
private int _count = 0;
public void Increment()
{
lock (_lockObject) // only ONE thread at a time can enter this block
{
_count++;
}
}
}
This is exactly the solution I mentioned for the race condition with _count++ - lock guarantees that the whole read-add-write operation runs atomically with respect to other threads trying to enter the same lock.
What happens "under the hood":
// lock (_lockObject) { _count++; } compiles roughly to:
bool lockTaken = false;
try
{
Monitor.Enter(_lockObject, ref lockTaken);
_count++;
}
finally
{
if (lockTaken) Monitor.Exit(_lockObject);
}
Key limitations of lock:
- Works only within one process (one application) - another process has no way to "see" that lock
- Blocks exactly one thread at a time (like a Mutex with a count of 1, but without any configurability)
- You can't use await inside a lock - this is a common trap in interviews:
lock (_lockObject)
{
await SomeAsyncMethod(); // ❌ Compile error: "cannot await in the body of a lock statement"
}
This limitation arises because a lock must be released on the same thread that acquired it - await can resume execution on a different thread (as we discussed with SynchronizationContext), which would break that guarantee.
Mutex - like lock, but across processes
Mutex (Mutual Exclusion) is synchronisation at the operating system level - it can work not only between threads in one process, but between different processes on the same computer.
// A named Mutex - visible to ALL processes in the system under that name
using var mutex = new Mutex(false, "Global\\MyApp_SingleInstanceMutex");
if (mutex.WaitOne(TimeSpan.Zero)) // try to take the mutex, don't wait long
{
try
{
// Only ONE instance of the application in the whole system will run this code at a time
RunApplication();
}
finally
{
mutex.ReleaseMutex(); // you MUST release it manually
}
}
else
{
Console.WriteLine("The application is already running!");
}
A classic use - enforcing a single instance of an application on a computer (a Named Mutex visible globally in the system):
static void Main()
{
using var mutex = new Mutex(true, "Global\\MyWpfApp", out bool isNewInstance);
if (!isNewInstance)
{
MessageBox.Show("The application is already running!");
return; // close this second instance
}
// normalny start aplikacji WPF
}
An important difference from lock - who can release:
mutex.ReleaseMutex(); // MUST be called by the SAME thread that called WaitOne()
// inaczej: SynchronizationLockException
Cost: Mutex is much slower than lock, because it requires a trip into the operating system kernel (kernel mode) even with no contention for the resource - lock/Monitor without contention works entirely in user mode, without calling the operating system, which is why it is faster.
Semaphore/SemaphoreSlim - allows MANY concurrent threads (not just one)
This is a fundamental conceptual difference from lock/Mutex - a semaphore doesn't restrict to one thread, but to a specified number of concurrent threads.
// At most 3 threads can execute the semaphore-protected code at the same time
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(3, 3); // (initial number of slots, maximum)
public async Task ProcessOrderAsync(Order order)
{
await _semaphore.WaitAsync(); // waits until a "slot" becomes free
try
{
await CallExternalApiAsync(order); // e.g. a limit of 3 concurrent requests to an external API
}
finally
{
_semaphore.Release(); // frees the "slot" for the next thread
}
}
A classic use: limiting the number of concurrent operations (throttling) - e.g. when an external API allows at most N concurrent requests:
private readonly SemaphoreSlim _apiThrottle = new SemaphoreSlim(5); // max 5 naraz
public async Task<List<OrderDto>> FetchAllOrdersAsync(List<int> orderIds)
{
var tasks = orderIds.Select(async id =>
{
await _apiThrottle.WaitAsync();
try
{
return await _httpClient.GetFromJsonAsync<OrderDto>($"api/orders/{id}");
}
finally
{
_apiThrottle.Release();
}
});
return (await Task.WhenAll(tasks)).ToList();
}
Even though you start, say, 100 requests at once (Task.WhenAll), the semaphore guarantees that at most 5 of them actually run concurrently - the rest wait in a queue on WaitAsync().
SemaphoreSlim vs Semaphore - which version
var semaphoreSlim = new SemaphoreSlim(3); // ✅ preferowany - lekki, tylko w ramach procesu, wspiera async
var semaphore = new Semaphore(3, 3, "Global\\MySemaphore"); // named, across processes, but SLOWER
SemaphoreSlim (added in .NET 4) is lighter and supports WaitAsync() (key - unlike lock, a semaphore can safely be combined with await), but works only within one process. The plain Semaphore can be named (across processes, like Mutex), but is much slower.
This is, incidentally, the key practical advantage of a semaphore over lock in asynchronous code:
// ❌ lock - you CANNOT use await inside
lock (_lockObject) { await SomeAsyncMethod(); } // compile error
// ✅ SemaphoreSlim - you CAN use await
await _semaphore.WaitAsync();
try { await SomeAsyncMethod(); } // OK!
finally { _semaphore.Release(); }
This is also a common reason why in modern, asynchronous .NET code (Web API) people use SemaphoreSlim(1, 1) instead of lock when the protected code has to contain an await:
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1); // odpowiednik "async lock"
public async Task UpdateCacheAsync()
{
await _semaphore.WaitAsync();
try
{
var freshData = await _apiClient.GetDataAsync(); // an await inside - impossible with lock
_cache = freshData;
}
finally
{
_semaphore.Release();
}
}
Comparison table
lock |
Mutex |
Semaphore/SemaphoreSlim |
|
|---|---|---|---|
| How many threads at once | 1 | 1 | N (configurable) |
| Scope | One process | Can be across processes (named) | SemaphoreSlim: one process; Semaphore: can be named |
Support for await |
❌ No | ❌ No (WaitOne is blocking) |
✅ Yes (WaitAsync in SemaphoreSlim) |
| Performance | Fastest (user mode) | Slower (kernel mode) | SemaphoreSlim: fast; Semaphore: slower |
| Who can release | Must be the same thread (through lock/Monitor) |
Must be the same thread | Can be released by a DIFFERENT thread than the one that waited |
| Typical use | Protecting shared in-memory state (like _count in a Singleton) |
A single instance of an application, synchronisation across processes | Throttling/limiting concurrent operations (e.g. HTTP requests) |
Tying back to the earlier conversation about Singleton/thread-safety
If you have a Singleton with mutable state:
public class CacheService // zarejestrowany jako Singleton
{
private readonly Dictionary<string, object> _cache = new(); // NIE thread-safe samo z siebie
private readonly SemaphoreSlim _lock = new SemaphoreSlim(1, 1);
public async Task<object> GetOrAddAsync(string key, Func<Task<object>> factory)
{
if (_cache.TryGetValue(key, out var cached)) return cached;
await _lock.WaitAsync();
try
{
if (_cache.TryGetValue(key, out cached)) return cached; // double-check after entering the critical section
var value = await factory(); // an await inside - hence SemaphoreSlim, not lock
_cache[key] = value;
return value;
}
finally
{
_lock.Release();
}
}
}
This is a real pattern ("double-checked locking" with an asynchronous semaphore) - exactly the kind of code you have to write correctly when a Singleton has mutable, shared state and needs asynchronous operations when modifying it.
Summary - which one when
lock- the default choice for simple protection of a critical section without anawaitinside, within one process - the fastest.Mutex- when you need synchronisation between processes (e.g. a single instance of an application) - used less often in typical application code.SemaphoreSlim- when you need (a) to limit the number of concurrent operations to more than one (throttling), or (b) to protect a section of code that contains anawait(then even with a limit of 1, as an "async-friendly lock").