Using the SemaphoreSlim construct
This recipe will show how to SemaphoreSlim
is a lightweight version of Semaphore
; it limits the number of threads that can access a resource concurrently.
Getting ready
To step through this recipe, you will need Visual Studio 2012. There are no other prerequisites. The source code for this recipe could be found at BookSamples\Chapter2\Recipe3
.
How to do it...
To understand limiting a multithreaded access to a resource with the help of the SemaphoreSlim
construct, perform the following steps:
- Start Visual Studio 2012. Create a new C# Console Application project.
- In the
Program.cs
file add the followingusing
directives:using System; using System.Threading;
- Below the
Main
method, add the following code snippet:static SemaphoreSlim _semaphore = new SemaphoreSlim(4);
static void AccessDatabase(string name, int seconds) { Console.WriteLine("{0} waits to access a database", name); _semaphore.Wait(); Console.WriteLine("{0} was granted an access to...