Sunday, February 9, 2025

Semaphore Vs Semaphore Slim

 

Semaphore vs SemaphoreSlim in C#

What is a Semaphore?

A Semaphore is a synchronization primitive used to control access to a shared resource by multiple threads. It works by maintaining a count that represents the number of available slots for accessing the resource. When a thread enters, the count decreases, and when it leaves, the count increases.

What is SemaphoreSlim?

SemaphoreSlim is a lightweight, managed implementation of Semaphore, introduced in .NET Framework 4. It provides better performance and is optimized for cases where a semaphore is needed within a single process.


Why Use Semaphore and SemaphoreSlim?

  1. To limit concurrent access to a resource
    Example: Controlling access to a database connection pool or an API rate limit.

  2. To prevent race conditions
    Example: Ensuring that only a limited number of threads can modify a shared collection at a time.

  3. To manage multi-threaded access in an efficient way
    Example: Restricting simultaneous file writes to avoid corruption.


    Semaphore vs SemaphoreSlim - Key Differences 🚀

    FeatureSemaphore 🏢SemaphoreSlim 🚀
    ScopeWorks across multiple processesWorks within a single process
    ImplementationUses OS-level (kernel-based) synchronizationUses user-mode synchronization (managed by .NET)
    PerformanceSlower due to kernel transitionsFaster as it avoids kernel overhead
    Async SupportDoes not support async/awaitSupports async/await for better responsiveness
    Use CaseInter-process synchronization (e.g., shared system resources)Within-process synchronization (e.g., limiting concurrent API calls, database access)
    Blocking vs Non-BlockingBlocks threads while waitingUses async wait, avoiding thread blocking
    Wait Handle Support✅ Supports WaitOne(), WaitAll()❌ Does not support WaitHandle methods

    When to Use?

    Use Semaphore when you need to synchronize across different applications (e.g., OS-wide named semaphores).
    Use Semaphore Slim when you need a lightweight, high-performance synchronization within a single process, especially with async/await.

    Note: semaphore slim  I used in in memory caching for single process so save dB calls and we give users to fast response.
    while semaphore is used for allow or control to multiple processes like if we have to run only two than we can control with that 
    InMemory caching: In Memory Caching in .Net

No comments:

Post a Comment

How to Do Cross-Browser Testing on Windows — Including Safari via Playwright

To test follow few steps: Step 1. Install node Step 2. create Folder and run these commands commands Copy Code ...