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 ...
随机推荐
- 查看FPM在你的机子上的平均内存占用情况
ps --no-headers -o "rss,cmd" -C php-fpm | awk '{ sum+=$1 } END { printf ("%d%s\n" ...
- 第十八节:Scrapy爬虫框架之settings文件详解
# -*- coding: utf-8 -*- # Scrapy settings for maoyan project## For simplicity, this file contains on ...
- jquery 修改input输入框的 readOnly属性 && input输入框隐藏
html的代码 <div class="control-group"> <label class="control-label required&quo ...
- HDU 6446 Tree and Permutation(赛后补题)
>>传送门<< 分析:这个题是结束之后和老师他们讨论出来的,很神奇:刚写的时候一直没有注意到这个是一个树这个条件:和老师讨论出来的思路是,任意两个结点出现的次数是(n-1)!, ...
- <mongoose>……find与findOne的区别……//
mongoose中的 find 和 findOne 都是用来查找指定表的数据的 find指的是查找指定表的所有数据,返回的是数组 User.find().then((result)=>{ con ...
- RS232
RS232的最大的传输速率大约10KBytes/s. 全双工工作方式,异步.数据是8位作为一块来发送的,先发送最低位,最后发送最高位. 在232通信中: Both side of the cable ...
- String类的概述和构造方法
StringDemo.java /* * String:字符串类 * 由多个字符组成的一串数据 * 字符串其本质就是一个字符数组 * * 构造方法: * String(String original) ...
- Leetcode 150.逆波兰表达式求值
逆波兰表达式求值 根据逆波兰表示法,求表达式的值. 有效的运算符包括 +, -, *, / .每个运算对象可以是整数,也可以是另一个逆波兰表达式. 说明: 整数除法只保留整数部分. 给定逆波兰表达式总 ...
- spark streaming 踩过的那些坑
系统背景 spark streaming + Kafka高级API receiver 目前资源分配(现在系统比较稳定的资源分配),独立集群 --driver-memory 50G --exec ...
- ORACLE RAC with NFS install
第一步:建立第一台节点机1).拷贝一台虚拟机做第一个节点,增加host-only的网卡 kudzu工具识别网卡(两都host-only是可以的).然后以下步骤修改相应的配置.etc/hosts内容如下 ...