SemaphoreSlim
https://msdn.microsoft.com/en-us/library/system.threading.semaphoreslim(v=vs.110).aspx
Represents a lightweight alternative to Semaphore that limits the number of threads that can access a resource or pool of resources concurrently.
Remarks
Semaphores are of two types: local semaphores and named system semaphores.
The former is local to an app. The latter is visible throughout the operating system and is suitable for inter-process synchronization.
The SemaphoreSlim is a lightweight alternative to the Semaphore class that doesn't use Windows kernel semaphores.
Unlike the Semaphore class, the SemaphoreSlim class doesn’t support named system semaphores.
You can use it as a local semaphore only.
The SemaphoreSlim class is the recommended semaphore for synchronization within a single app.
A lightweight semaphore controls access to a pool of resources that is local to your application.
When you instantiate a semaphore, you can specify the maximum number of threads that can enter the semaphore concurrently.
You also specify the initial number of threads that can enter the semaphore concurrently. This defines the semaphore's count.
The count is decremented each time a thread enters the semaphore, and incremented each time a thread releases the semaphore.
To enter the semaphore, a thread calls one of the Wait or WaitAsync overloads.
To release the semaphore, it calls one of the Release overloads.
When the count reaches zero, subsequent calls to one of the Wait methods block until other threads release the semaphore.
If multiple threads are blocked, there is no guaranteed order, such as FIFO or LIFO, that controls when threads enter the semaphore.
The basic structure for code that uses a semaphore to protect resources is:
' Enter semaphore by calling one of the Wait or WaitAsync methods.
SemaphoreSlim.Wait()
'
' Execute code protected by the semaphore.
'
SemaphoreSlim.Release()
When all threads have released the semaphore, the count is at the maximum value specified when the semaphore was created.
The semaphore's count is available from the CurrentCount property.
Important
The SemaphoreSlim class doesn’t enforce thread or task identity on calls to the Wait, WaitAsync, and Release methods.
In addition, if the SemaphoreSlim(Int32) constructor is used to instantiate the SemaphoreSlim object, the CurrentCount property can increase beyond the value set by the constructor.
It is the programmer's responsibility to ensure that calls to Wait or WaitAsync methods are appropriately paired with calls to Release methods.
Example
The following example creates a semaphore with a maximum count of three threads and an initial count of zero threads.
The example starts five tasks, all of which block waiting for the semaphore.
The main thread calls the Release(Int32) overload to increase the semaphore count to its maximum, which allows three tasks to enter the semaphore.
Each time the semaphore is released, the previous semaphore count is displayed. Console messages track semaphore use.
The simulated work interval is increased slightly for each thread to make the output easier to read.
public class Example
{
private static SemaphoreSlim semaphoreSlim; private static int padding; internal static void Method()
{
//Create the semaphore.
semaphoreSlim = new SemaphoreSlim(, );
Console.WriteLine("{0} tasks can enter the semaphore.", semaphoreSlim.CurrentCount); Task[] tasks = new Task[]; // Create and start five numbered tasks.
for (int i = ; i <= ; i++)
{
tasks[i] = Task.Run(() =>
{
// Each task begins by requesting the semaphore.
Console.WriteLine("Task {0} begins and waits for the semaphore.", Task.CurrentId);
semaphoreSlim.Wait(); Interlocked.Add(ref padding, ); Console.WriteLine("Task {0} enters the semaphore.", Task.CurrentId); // The task just sleeps for 1+ seconds.
Thread.Sleep( + padding); Console.WriteLine("Task {0} releases the semaphore; previous count: {1}.", Task.CurrentId, semaphoreSlim.Release());
});
} // Wait for half a second, to allow all the tasks to start and block.
Thread.Sleep(); // Restore the semaphore count to its maximum value.
Console.Write("Main thread calls Release(3) --> ");
semaphoreSlim.Release();
Console.WriteLine("{0} tasks can enter the semaphore.", semaphoreSlim.CurrentCount);
// Main thread waits for the tasks to complete.
Task.WaitAll(tasks); Console.WriteLine("Main thread exits.");
}
}
SemaphoreSlim的更多相关文章
- 【C#】【Thread】Semaphore/SemaphoreSlim信号量
System.Threading.Semaphore 类表示一个命名(系统范围)信号量或本地信号量. 它是一个对 Win32 信号量对象的精简包装. Win32 信号量是计数信号量,可用于控制对资源池 ...
- C#并行编程 (Barrier,CountdownEvent,ManualResetEventSlim,SemaphoreSlim,SpinLock,SpinWait )
背景 有时候必须访问变量.实例.方法.属性或者结构体,而这些并没有准备好用于并发访问,或者有时候需要执行部分代码,而这些代码必须单独运行,这是不得不通过将任务分解的方式让它们独立运行. 当任务和线程要 ...
- 第十三节:实际开发中使用最多的监视锁Monitor、lock语法糖的扩展、混合锁的使用(ManualResetEvent、SemaphoreSlim、ReaderWriterLockSlim)
一. 监视锁(Monitor和lock) 1. Monitor类,限定线程个数的一把锁,两个核心方法: Enter:锁住某个资源. Exit:退出某一个资源. 测试案例:开启5个线程同时对一个变量进行 ...
- C# SemaphoreSlim 实现
当多个任务或线程并行运行时,难以避免的对某些有限的资源进行并发的访问.可以考虑使用信号量来进行这方面的控制(System.Threading.Semaphore)是表示一个Windows内核的信号量对 ...
- 《C#多线程编程实战》2.4 SemaphoreSlim
这个简单多了. 理解也是很好理解. 比上一个mutex好理解多了. 这个SemaphoreSlim是干什么呢? 就是限制线程的来访问. 好比说一次只有两个,一次只有三个 这样的线程来访问资源. 有点 ...
- Semaphore and SemaphoreSlim
https://msdn.microsoft.com/en-us/library/z6zx288a(v=vs.110).aspx The System.Threading.Semaphore clas ...
- 一次 .NET Core 中玩锁的经历:ManualResetEventSlim, Semaphore 与 SemaphoreSlim
最近同事对 .net core memcached 缓存客户端 EnyimMemcachedCore 进行了高并发下的压力测试,发现在 linux 上高并发下使用 async 异步方法读取缓存数据会 ...
- Mutex vs Semaphore vs Monitor vs SemaphoreSlim
C#开发者(面试者)都会遇到Mutex,Semaphore,Monitor,SemaphoreSlim这四个与锁相关的C#类型,本文期望以最简洁明了的方式阐述四种对象的区别. 线程安全 教条式理解 如 ...
- SemaphoreSlim 实现
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/dz45693/article/deta ...
随机推荐
- Git 教程 -- 第一天
什么是Git? Git是一个开源的分布式版本控制系统,可以有效.高速的处理从很小到非常大的项目版本管理. 为什么使用Git? 众所周知,版本控制系统分为集中式版本控制系统(SVN.CVS等)与分布式版 ...
- Centos6.8 安装mongo3.6以及权限配置和开启外网链接
目录 安装环境和版本说明,以及参考文档链接 安装MongoDB数据库 运行MongoDB数据库 删除卸载MongoDB 配置MongoDB管理员用户 修改配置文件,允许外网链接 安装配置完成,使用Ro ...
- Mysql 字符函数详解
MySql 所有字符串函数函数详解 ASCII(str) 返回str最左边第一位字符的ASCII编码,如果str为空,则返回 0 .如果str为NULL,则返回NULL -- 只返回a的ASCII编码 ...
- [Python3网络爬虫开发实战] 1.2.4-GeckoDriver的安装
上一节中,我们了解了ChromeDriver的配置方法,配置完成之后便可以用Selenium驱动Chrome浏览器来做相应网页的抓取. 那么对于Firefox来说,也可以使用同样的方式完成Seleni ...
- web应用无法访问的原因之一以及如何设置数据库编码
这篇随笔,本是应该是在前天晚上发的,但是因为事情太多,硬生生拖到了现在,当时,在我将web应用部署到服务器上时,在调用接口时,客户端没有任何反应,应该是又出异常了,查看了控制台的异常输出,提示requ ...
- Error: Divergence detected in AMG solver: k
** Error: Divergence detected in AMG solver: k A:Since you were working on convergence issue from pa ...
- Python基础—线程、进程和协程
今天已是学习Python的第十一天,来干一碗鸡汤继续今天的内容,今天的鸡汤是:超越别人对你的期望.本篇博客主要介绍以下几点内容: 线程的基本使用: 线程的锁机制: 生产者消费之模型(队列): 如何自定 ...
- Webdriver元素定位1
元素的定位应该是自动化测试的核心,要想操作一个元素,首先应该识别这个元素. webdriver提供了一系列的元素定位方法,常用的有以下几种: id name class name tag link t ...
- Android SwipeSelector
Android SwipeSelector Android SwipeSelector是github上一个第三方开源的项目,其项目主页:https://github.com/roughike/S ...
- Microsoft Excel 准确按照一页的宽度和高度打印
设置 Microsoft Excel 准确按照一页的宽度和高度打印 Sheet1. VBA复制 With Worksheets("Sheet1").PageSetup .Zoo ...