- Multithreading in C# 5.0 Cookbook
- Eugene Agafonov
- 364字
- 2021-07-21 18:10:01
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 a database",name); Thread.Sleep(TimeSpan.FromSeconds(seconds)); Console.WriteLine("{0} is completed", name); _semaphore.Release(); }
- Inside the
Main
method, add the following code snippet:for (int i = 1; i <= 6; i++) { string threadName = "Thread " + i; int secondsToWait = 2 + 2*i; var t = new Thread(() => AccessDatabase(threadName, secondsToWait)); t.Start(); }
- Run the program.
How it works...
When the main program starts, it creates a SemaphoreSlim
instance, specifying the number of concurrent threads allowed in its constructor. Then it starts six threads with different names and start times to run.
Every thread is trying to acquire an access to a database, but we restrict the number of concurrent accesses to a database by four threads with the help of a semaphore. When four threads get an access to a database, the other two threads wait until one of the previous threads finishes its work and signals by calling the _semaphore.Release
method.
There's more…
Here we use a hybrid construct, which allows us to save a context switch in cases where the wait time is less. However, there is an older version of this construct called Semaphore
. This version is a pure, kernel-time construct. There is no sense in using it, except in one very important scenario; we can create a named semaphore like a named mutex and use it to synchronize threads in different programs. SemaphoreSlim
does not use Windows kernel semaphores and does not support interprocess synchronization, so use Semaphore
in this case.
- The Android Game Developer's Handbook
- Python從入門到精通(精粹版)
- PHP+MySQL+Dreamweaver動態網站開發實例教程
- 精通網絡視頻核心開發技術
- Java網絡編程實戰
- Django實戰:Python Web典型模塊與項目開發
- JavaScript程序設計:基礎·PHP·XML
- Python計算機視覺和自然語言處理
- Practical GIS
- 軟件測試分析與實踐
- Mastering Machine Learning with R
- 體驗之道:從需求到實踐的用戶體驗實戰
- Building Apple Watch Projects
- ASP.NET本質論
- 基于JavaScript的WebGIS開發