Using the SemaphoreSlim construct
This recipe will show you how to limit multithreaded access to some resources with the help of the SemaphoreSlim
construct. 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 2015. There are no other prerequisites. The source code for this recipe can be found at BookSamples\Chapter2\Recipe3
.
How to do it...
To understand how to limit a multithreaded access to a resource with the help of the SemaphoreSlim
construct, perform the following steps:
Start Visual Studio 2015. Create a new C# console application project.
In the
Program.cs
file, add the followingusing
directives:using System; using System.Threading; using static System.Console; using static System.Threading.Thread;
Below the
Main
method, add the following code snippet:static SemaphoreSlim _semaphore = new SemaphoreSlim(4); static void AccessDatabase(string name...