🧵 .NET Pro Tip: Use SemaphoreSlim for Thread Synchronization

Pro tip with short notes

DotNet Full Stack Dev
1 min readOct 13, 2024

When you need to limit access to a resource shared by multiple threads, SemaphoreSlim is a great tool to control concurrency. It allows a specific number of threads to access a resource concurrently, making it useful in scenarios where you want to avoid race conditions but still allow limited parallelism.

📌Explore more at: https://dotnet-fullstack-dev.blogspot.com/
🌟 Clapping would be appreciated! 🚀

// Initialize SemaphoreSlim with a max count of 2
private static readonly SemaphoreSlim semaphore = new SemaphoreSlim(2);

public async Task AccessSharedResourceAsync(int taskId)
{
// Wait until it's safe to proceed
await semaphore.WaitAsync();
try
{
// Simulate resource access
Console.WriteLine($"Task {taskId} is accessing the shared resource.");
await Task.Delay(1000); // Simulate work
}
finally
{
// Release the semaphore so another thread can enter
semaphore.Release();
}
}

// Usage example
for (int i = 1; i <= 5; i++)
{
_ = AccessSharedResourceAsync(i);
}

📌 Highlights:

  • SemaphoreSlim allows a specific number of threads to access a shared resource at a time.
  • Helps prevent race conditions while allowing limited concurrent access, making it ideal for scenarios like file access or database connections.

--

--

DotNet Full Stack Dev
DotNet Full Stack Dev

Written by DotNet Full Stack Dev

Join me to master .NET Full Stack Development & boost your skills by 1% daily with insights, examples, and techniques! https://dotnet-fullstack-dev.blogspot.com

No responses yet