0
0
CsharpConceptBeginner · 3 min read

SemaphoreSlim in C#: What It Is and How to Use It

SemaphoreSlim in C# is a lightweight synchronization tool that controls how many threads can access a resource at the same time. It helps manage concurrent tasks by limiting the number of threads allowed to enter a critical section, improving performance and avoiding conflicts.
⚙️

How It Works

Imagine a small room with a limited number of chairs. Only a certain number of people can sit inside at once. If the room is full, others must wait outside until someone leaves. SemaphoreSlim works like this room, controlling how many threads can enter a part of your program simultaneously.

It keeps a count of how many threads are allowed inside. When a thread wants to enter, it asks the semaphore. If there is space (count is not zero), the thread enters and the count decreases. When the thread finishes, it leaves and increases the count, allowing others to enter.

This mechanism helps prevent too many threads from running a sensitive part of code at the same time, which could cause errors or slow performance.

💻

Example

This example shows how SemaphoreSlim limits access to a resource so only two threads can run a task at the same time.

csharp
using System;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static SemaphoreSlim semaphore = new SemaphoreSlim(2); // Allow 2 threads

    static async Task AccessResource(int id)
    {
        Console.WriteLine($"Task {id} waiting to enter...");
        await semaphore.WaitAsync(); // Wait for permission

        Console.WriteLine($"Task {id} entered.");
        await Task.Delay(1000); // Simulate work

        Console.WriteLine($"Task {id} leaving.");
        semaphore.Release(); // Release permission
    }

    static async Task Main()
    {
        Task[] tasks = new Task[5];
        for (int i = 0; i < 5; i++)
        {
            int taskId = i + 1;
            tasks[i] = AccessResource(taskId);
        }
        await Task.WhenAll(tasks);
    }
}
Output
Task 1 waiting to enter... Task 2 waiting to enter... Task 3 waiting to enter... Task 4 waiting to enter... Task 5 waiting to enter... Task 1 entered. Task 2 entered. Task 1 leaving. Task 3 entered. Task 2 leaving. Task 4 entered. Task 3 leaving. Task 5 entered. Task 4 leaving. Task 5 leaving.
🎯

When to Use

Use SemaphoreSlim when you want to limit how many threads can access a resource or run a piece of code at the same time. This is useful when the resource is limited, like a database connection, file access, or network calls.

It helps avoid problems like too many threads causing slowdowns, crashes, or data corruption. For example, if you have a web server handling many requests, you might use SemaphoreSlim to limit how many requests access a database simultaneously.

Key Points

  • SemaphoreSlim controls concurrent access by limiting the number of threads.
  • It is lightweight and designed for asynchronous programming with WaitAsync.
  • Use it to protect limited resources and improve performance.
  • Always release the semaphore after the work is done to avoid deadlocks.

Key Takeaways

SemaphoreSlim limits how many threads can access a resource at once to prevent conflicts.
It supports asynchronous waiting with WaitAsync for efficient thread management.
Use SemaphoreSlim to protect limited resources like files, databases, or network calls.
Always release the semaphore after use to allow other threads to proceed.