Updated on
A semaphore in C# lets a fixed number of threads run a piece of code at the same time and makes every other thread wait for a free slot. .NET gives us two of them: Semaphore, which can also coordinate processes on Windows, and SemaphoreSlim, a lighter type for a single process that can wait asynchronously.
We’ll build both on the same example, measure how differently the two of them wait, and then go through the best practices for using semaphores.
Let’s start.
What Is a Semaphore in C#?
A semaphore in C# is a counter that decides how many threads may run a protected piece of code at the same time. Each thread that enters takes one slot from the counter, and each thread that leaves gives one back. When the counter reaches zero, the next thread waits until another thread releases a slot.
The Semaphore class in C# is another mechanism to synchronize a thread’s access to shared resources. It’s more flexible than lock and mutex because it’s not confined to the context that defines it. In other words, the thread or process that acquires the synchronization handle can differ from the one that releases it.
Microsoft Learn’s “Semaphore and SemaphoreSlim” page states that both types “don’t enforce thread identity on calls to the WaitOne, Wait, Release, and SemaphoreSlim.Release methods.” For this reason, semaphores support a wider range of synchronization scenarios, such as one thread that always waits and another that always releases.
Let’s analyze the Semaphore class in more detail.
Initializing Semaphore C# Class
When using semaphores, we can define the maximum number of threads our code will allow to access a protected resource or critical section of code. This is an improvement over lock and mutex which allow only a single thread. When defining a semaphore we can specify these settings:
var semaphore = new Semaphore(initialCount: 2, maximumCount: 3);
Here, we create a semaphore that allows a maximum of three threads to access shared resources in parallel and we initially set the counter to two. This is like a section of code allowing access to three ticket holders.
After creating a semaphore, we can call semaphore.WaitOne() for the running thread to access the protected code. This will also reduce the semaphore’s internal counter by one.
Once the thread is done with the critical operations, our code can call semaphore.Release() to free up a synchronization handle. This will increase the semaphore’s internal counter.Â
There is also a semaphore.Release(int count) variation of this method to increase the counter more than once.
If the semaphore’s internal counter is zero, any thread that calls semaphore.WaitOne() will wait for another thread to call semaphore.Release(). In scenarios where access is frequently blocked, inefficiencies can occur because the semaphore will block synchronously any waiting threads.
Everything that we’ve discussed so far works for threads of a single process, and we refer to these types of semaphores as local ones.
Named Semaphores
Named semaphores allow us to achieve synchronization of threads of different processes. This is similar to what we can achieve with mutex.Â
A named semaphore is an operating system object, so it can reach other processes on the same machine and nothing beyond it. By default, only processes in the same login session see the name, and a Global\ prefix on the name opens it to the whole machine. It’s also a Windows feature. Microsoft Learn’s page for the Semaphore constructors says that on Unix-based operating systems “named semaphores are not supported”, so a named semaphore only fits code that runs on Windows.
We can create a named semaphore by setting the name as a constructor parameter:
var namedSemaphore = new Semaphore(initialCount: 3, maximumCount: 3, "SemaphoreName");
All other features of local semaphores also apply in the case of named semaphores.Â
Let’s see how a local semaphore performs thread synchronization. Mind you, WaitOne() blocks the thread that calls it, even inside an async method like this one, so production async code shouldn’t copy this part:
public class ExampleWithSemaphore
{
private static readonly ConcurrentQueue<string> _outputQueue = new();
private static readonly Semaphore _semaphore = new(initialCount: 3, maximumCount: 3);
public static async Task<IReadOnlyCollection<string>> AccessWithSemaphoreAsync(int sleepDelay)
{
var tasks = new Task[Constants.NumberOfThreads];
for (int i = 0; i < Constants.NumberOfThreads; i++)
{
var processParams = new ProcessParams(i, sleepDelay);
var task = WorkerWithSemaphoreAsync(processParams);
tasks[i] = task;
}
await Task.WhenAll(tasks);
return _outputQueue;
}
static async Task WorkerWithSemaphoreAsync(ProcessParams processParams)
{
_semaphore.WaitOne();
try
{
await Task.Delay(processParams.SleepDelay);
var output = string.Format("Semaphore: Thread {0} is accessing {1} at {2}",
processParams.SequenceNo,
nameof(_outputQueue),
DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture));
_outputQueue.Enqueue(output);
}
finally
{
_semaphore.Release();
}
}
}
Here, we initialize a semaphore and set both the initial count and maximum count to three. The method AccessWithSemaphoreAsync() uses a loop to create several Tasks that will execute concurrently. It also adds them to a Task[] and waits for their completion.
Each thread calls the WorkerWithSemaphoreAsync() method once. The commands _semaphore.WaitOne() and _semaphore.Release() control access to the shared resource that is a ConcurrentQueue that holds values that each concurrent task generates. We also call await Task.Delay(processParams.SleepDelay) to mock a long-running operation as if our application was making a network call. We release the semaphore in a finally block, so the slot goes back even if the work in between throws an exception.
Let’s run our code and see the output:
Executing with Semaphore... Semaphore: Thread 1 is accessing _outputQueue at 2026-11-13 12:12:56.219 Semaphore: Thread 0 is accessing _outputQueue at 2026-11-13 12:12:56.219 Semaphore: Thread 2 is accessing _outputQueue at 2026-11-13 12:12:56.219 Semaphore: Thread 3 is accessing _outputQueue at 2026-11-13 12:12:56.279 Semaphore: Thread 4 is accessing _outputQueue at 2026-11-13 12:12:56.279 Semaphore: Thread 5 is accessing _outputQueue at 2026-11-13 12:12:56.279 Semaphore: Thread 8 is accessing _outputQueue at 2026-11-13 12:12:56.341 Semaphore: Thread 7 is accessing _outputQueue at 2026-11-13 12:12:56.341 Semaphore: Thread 6 is accessing _outputQueue at 2026-11-13 12:12:56.341 Semaphore: Thread 9 is accessing _outputQueue at 2026-11-13 12:12:56.403
The thread numbers and timestamps will be different on every run. Microsoft Learn notes that no guaranteed order decides which blocked thread enters the semaphore next. The groups of three show up in every run.
We observe here that tasks complete their execution in groups of three. This is because our semaphore allows up to three threads to gain access to the critical section of code. Such parallelism is not possible when using lock or mutex. Generally speaking, the more parallelism we can allow, the better execution times we’ll get.
However, as we mentioned, every time a thread calls semaphore.WaitOne() and the semaphore’s counter is zero, the execution will be blocked and our program will feel less responsive. For this reason, we can opt to use the SemaphoreSlim class instead, which we’ll be looking at next.
The SemaphoreSlim C# Class
SemaphoreSlim is a variation of semaphore that enables us to instruct threads to wait asynchronously when other threads have gained access to the protected resource. SemaphoreSlim works with a Task-based API allowing us to use async and await.Â
As its name also indicates, SemaphoreSlim is a lightweight type of semaphore that only works for threads of a single application. SemaphoreSlim does not support named semaphores and different processes cannot share the same SemaphoreSlim synchronization handle.
Initializing SemaphoreSlim Class
We can create a SemaphoreSlim object supplying the initial count and maximum count:
var semaphoreSlim = new SemaphoreSlim(initialCount: 3, maxCount: 3);
Here, we create a SemaphoreSlim object which allows a maximum of three threads to access shared resources in parallel and we initially set the counter to three.
A thread can enter the protected code by calling await semaphoreSlim.WaitAsync(). This will also decrease the semaphore’s internal counter. More importantly, when the counter is zero the executing thread will have to wait asynchronously. This is a great benefit for our code as the .NET runtime can use the thread to execute other pieces of code while waiting for another thread to increase the counter of the semaphoreSlim object by calling semaphoreSlim.Release().
Let’s see how SemaphoreSlim manages synchronization:
public class ExampleWithSemaphoreSlim
{
private static readonly ConcurrentQueue<string> _outputQueue = new();
private static readonly SemaphoreSlim _semaphoreSlim = new(initialCount: 3, maxCount: 3);
public static async Task<IReadOnlyCollection<string>> AccessWithSemaphoreSlimAsync(int sleepDelay)
{
var tasks = new Task[Constants.NumberOfThreads];
for (int i = 0; i < Constants.NumberOfThreads; i++)
{
var processParams = new ProcessParams(i, sleepDelay);
var task = WorkerWithSemaphoreSlimAsync(processParams);
tasks[i] = task;
}
await Task.WhenAll(tasks);
return _outputQueue;
}
static async Task WorkerWithSemaphoreSlimAsync(ProcessParams processParams)
{
await _semaphoreSlim.WaitAsync();
try
{
await Task.Delay(processParams.SleepDelay);
var output = string.Format("SemaphoreSlim: Thread {0} is accessing {1} at {2}",
processParams.SequenceNo,
nameof(_outputQueue),
DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture));
_outputQueue.Enqueue(output);
}
finally
{
_semaphoreSlim.Release();
}
}
}
Here, we initialize a SemaphoreSlim object with three slots. The method AccessWithSemaphoreSlimAsync() uses a loop to create several task objects that will run in parallel. It also adds them to a Task[] object to refer to them collectively later.
Each task is created by the method WorkerWithSemaphoreSlimAsync() that encloses the protected code. Here, all code is non-blocking. We are making use of the await keyword to call _semaphoreSlim.WaitAsync() and await Task.Delay(processParams.SleepDelay) to mock a long-running operation. Like before, the concurrent tasks write a value in the ConcurrentQueue.
Let’s run our code and observe the output:
Executing with SemaphoreSlim... SemaphoreSlim: Thread 2 is accessing _outputQueue at 2026-11-13 12:12:56.465 SemaphoreSlim: Thread 1 is accessing _outputQueue at 2026-11-13 12:12:56.465 SemaphoreSlim: Thread 0 is accessing _outputQueue at 2026-11-13 12:12:56.465 SemaphoreSlim: Thread 3 is accessing _outputQueue at 2026-11-13 12:12:56.526 SemaphoreSlim: Thread 5 is accessing _outputQueue at 2026-11-13 12:12:56.526 SemaphoreSlim: Thread 4 is accessing _outputQueue at 2026-11-13 12:12:56.526 SemaphoreSlim: Thread 8 is accessing _outputQueue at 2026-11-13 12:12:56.588 SemaphoreSlim: Thread 7 is accessing _outputQueue at 2026-11-13 12:12:56.588 SemaphoreSlim: Thread 6 is accessing _outputQueue at 2026-11-13 12:12:56.588 SemaphoreSlim: Thread 9 is accessing _outputQueue at 2026-11-13 12:12:56.650
Here, all threads completed their execution in a similar time as in our semaphore example, again in groups of three and again in an order that changes between runs. This is because again we allow three threads to gain access to the critical section of code. The big difference is that on await _semaphoreSlim.WaitAsync() our program’s threads are not blocked. The runtime can use the waiting threads in other parts of the system, allowing for better usage of the system’s resources.
Semaphore vs SemaphoreSlim: Which One Should We Use?
For code that runs inside one process, SemaphoreSlim is the one we want. It has WaitAsync(), so async code can wait for a slot without holding a thread, and its wait methods accept a timeout and a CancellationToken. It’s also lighter, because it relies on the runtime’s own synchronization primitives as much as it can, while Semaphore wraps an operating system semaphore on Windows.
Semaphore has no async wait. WaitOne() blocks whatever thread calls it until a slot frees up, and inside async code that’s a thread the runtime can’t use for anything else in the meantime.
Semaphore still wins in two places. A named Semaphore coordinates several processes on the same Windows machine, which SemaphoreSlim can’t do at all. And because Semaphore derives from WaitHandle, we can wait on it together with other handles through WaitHandle.WaitAny() or WaitHandle.WaitAll().
The counting rules are the same for both types: a wait takes a slot, a release gives it back, and neither type checks which thread does which.
Microsoft Learn does add a caveat. It describes SemaphoreSlim as a semaphore for waits that are expected to be short, because its synchronous Wait() spins for a moment before it blocks. When synchronous waits are long and unpredictable, the same page points to Semaphore, which doesn’t spin.
We can see the blocking with the code we already have. Each Access...Async() method starts its ten workers in a loop and hands its Task back to the caller at its first real await. So let’s time how long each call keeps the caller busy before that happens:
using IntroductionToSemaphoreInCsharp;
using System.Diagnostics;
const int SleepDelay = 50;
Console.WriteLine("Executing with Semaphore...");
var stopwatch = Stopwatch.StartNew();
var semaphoreTask = ExampleWithSemaphore.AccessWithSemaphoreAsync(SleepDelay);
var semaphoreBlockedMs = stopwatch.ElapsedMilliseconds;
var outputQueue = await semaphoreTask;
foreach (var output in outputQueue)
{
Console.WriteLine(output);
}
Console.WriteLine("Executing with SemaphoreSlim...");
stopwatch.Restart();
var semaphoreSlimTask = ExampleWithSemaphoreSlim.AccessWithSemaphoreSlimAsync(SleepDelay);
var semaphoreSlimBlockedMs = stopwatch.ElapsedMilliseconds;
outputQueue = await semaphoreSlimTask;
foreach (var output in outputQueue)
{
Console.WriteLine(output);
}
Console.WriteLine($"Semaphore kept the caller busy for {semaphoreBlockedMs} ms");
Console.WriteLine($"SemaphoreSlim kept the caller busy for {semaphoreSlimBlockedMs} ms");
Console.WriteLine("Calling Release multiple times...");
try
{
ExampleWithSemaphore.ReleaseMultipleTimes();
}
catch (SemaphoreFullException ex)
{
Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}
We read the stopwatch right after each call returns its task and before we await it. After the queue lines we’ve already seen, the program prints:
Semaphore kept the caller busy for 182 ms SemaphoreSlim kept the caller busy for 1 ms
Your numbers will differ from ours, while the gap between the two stays. With Semaphore, the loop that starts the workers calls WaitOne() itself, so every time the three slots are taken, the caller sits inside that call until a worker releases one. The caller only gets its task back once the last worker is in, after roughly three rounds of the 50 ms delay. With SemaphoreSlim, a worker that finds no free slot returns an unfinished task right away, and the caller is free almost at once. The sample’s tests check both sides: the Semaphore call keeps the caller busy for at least one delay, the SemaphoreSlim call for less than one.
Here are the differences side by side:
Semaphore | SemaphoreSlim |
|
|---|---|---|
| Works across processes | Yes, as a named semaphore, on Windows only | No, one process only |
| Wait without blocking a thread | No, WaitOne() always blocks | Yes, await WaitAsync() |
| Blocking wait | WaitOne() | Wait() |
| Timeout | Yes, WaitOne(timeout) | Yes, on Wait() and WaitAsync() |
CancellationToken | No | Yes, on Wait() and WaitAsync() |
| Maximum count | Required (maximumCount) | Optional (maxCount) |
| Releasing past the maximum | Throws SemaphoreFullException | Throws SemaphoreFullException; the default maxCount is int.MaxValue |
| Checks which thread releases | No | No |
Is a WaitHandle (WaitAny, WaitAll) | Yes | No |
| Built on | An operating system semaphore on Windows, the runtime's own wait code on Linux and macOS | Runtime primitives, kernel handle only when needed |
| Pick it when | Processes on one Windows machine share a limit, or we wait on several handles at once | Everything else, and always in async code |
If none of the Semaphore rows apply to our code, SemaphoreSlim is the safer default, and in async code it’s the only one of the two that fits.
The SemaphoreFullException Error
When calling semaphore.Release(), it’s our responsibility to ensure that we can still increase the internal counter without violating the maximum limit that we set up the semaphore object with.Â
Let’s see how calling semaphore.Release() multiple times can cause an error:
public static void ReleaseMultipleTimes()
{
using var semaphore = new Semaphore(initialCount: 2, maximumCount: 2);
semaphore.WaitOne();
semaphore.Release();
semaphore.Release();
}
Here, we create a semaphore object with an initialCount and maximumCount of two.Â
We then call semaphore.WaitOne() and the internal counter is reduced to one. Following that, we call semaphore.Release(), increasing the counter’s value to two.
Finally, we call semaphore.Release() once more and we see that our code throws a SemaphoreFullException as the counter cannot increase more than the maximum count.Â
Our Program.cs catches the exception and prints it:
Calling Release multiple times... SemaphoreFullException: Adding the specified count to the semaphore would cause it to exceed its maximum count.
SemaphoreSlim follows the same rule, but its default maximum is int.MaxValue. With new SemaphoreSlim(1), that default applies, so an extra Release() simply raises the count to two without an error. A bug that releases twice then lets two threads into code we meant for one, and nothing tells us. So when the limit matters, we pass maxCount.
Semaphores Best Practices
Let’s also see the best practices we should follow with semaphores to achieve optimal performance, avoid traps, and promote code maintainability.Â
Proper Initialization
We should choose the maximum and initial count wisely. A high maximum count can result in a high degree of parallelization and better performance. The trade-off is that every thread inside the semaphore runs at the same time as the others, so the code it protects has to be safe for that many threads at once. That’s why our examples write to a ConcurrentQueue, which is safe for many writers at once.
Choose the Right Semaphore Type
We should use the right semaphore type (Semaphore, SemaphoreSlim, Local, and Named Semaphores) depending on the needs of our code. We should be cautious with semaphores that span multiple processes (named semaphores). Another process that uses the same name shares our slots, whether we meant it to or not, and Microsoft Learn warns that malicious code on the same computer could use this for a denial-of-service attack. A named semaphore also does nothing for a second server, so it can’t coordinate a cluster. That needs a distributed lock, which no System.Threading type provides.
And when our threads mostly read shared data and rarely write it, a ReaderWriterLockSlim may fit better than any semaphore.
Wait and Release Correctly
We should always ensure that WaitOne/WaitAsync is matched with a Release. This way the semaphore count will remain accurate. We can use try/finally blocks to ensure that we call Release even if an exception occurs.
Our two workers do exactly that. Note that the wait sits before the try, not inside it: if WaitAsync() is canceled, it throws before the thread gets a slot, and the finally block must not give one back. A wait with a timeout returns false instead of throwing, so we check that result and enter the try only when it’s true.
Avoid Deadlocks
As semaphores instruct threads to block and wait they can easily cause deadlocks. We should ensure that all code paths that acquire a semaphore also release it. A timeout helps too. WaitAsync(TimeSpan) returns false when no slot frees up in time, so we can log the problem and back off instead of waiting forever.
In addition, we should avoid nested semaphores where possible, as acquiring multiple semaphores in different orders can lead to deadlocks. This will simplify the understanding of our code and will increase its maintainability.Â
Limit the Scope of Semaphores
For optimal performance, we should keep the semaphore’s scope as narrow as possible to avoid contention. We should use the semaphore to protect the least amount of code possible, exiting the block as fast as we can. We should prefer to use local or instance-level semaphores instead of global ones unless necessary.Â
Give Semaphore Objects Good Names
We should give semaphores names that document their purpose and behavior in our code to make it easier for others (and future us) to understand and maintain. Â
Consider Parallel.ForEachAsync for Simple Throttling
Sometimes all we want is to run an async operation over a collection with no more than a few calls at a time. In that case, we may not need a semaphore at all. Parallel.ForEachAsync takes a ParallelOptions object, and its MaxDegreeOfParallelism property caps how many items run at once. We should keep the semaphore for cases where the limit has to wrap code that isn’t one loop over one collection.
Conclusion
In this article, we introduced the C# Semaphore class that allows us to synchronize the access of threads and processes to critical pieces of code. We also looked at the SemaphoreSlim class and drew comparisons with the Semaphore class. In short, SemaphoreSlim is the default inside one process and the only choice in async code, while a named Semaphore is for processes that share a limit on one Windows machine.
Finally, we explored the best practices when using Semaphores in C# and .NET.
Tested with .NET 11.0.0 and MSTest 4.5.3.






