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 ...
随机推荐
- mysql8忘记登录密码时,修改密码方法
一.停止mysqld进程 systemctl stop mysqld.service 二.修改/etc/my.cnf(在mysqld选项添加skip-grant-tables),设置免密码登录: vi ...
- Python之面向对象反射
Python之面向对象反射 isinstance(obj,cls)检查是否obj是否是类 cls 的对象 1 class Foo(object): 2 pass 3 4 obj = Foo() 5 6 ...
- Linux下安装SVN,仓库创建,用户权限管理
Exported from Notepad++ Linux下安装SVN,仓库创建,用户权限管理 1.SVN安装 Ubuntu系统下安装:sudoapt-getinstallsubv ...
- 杭电 2111 Saving HDU (贪心)
Description 话说上回讲到海东集团面临内外交困,公司的元老也只剩下XHD夫妇二人了.显然,作为多年拼搏的商人,XHD不会坐以待毙的. 一天,当他正在苦思冥想解困良策的时候,突然想到了自己 ...
- SSH配置—Linux下实现免密码登录
首先,假设我们有两台服务器,服务器名称分别是 master 和 slave1,我们现在需要做的就是在服务器 master 上面登录 服务器 slave1 不需要输入密码就可以登录成功,如下图所示. 下 ...
- jar项目 BeanDefinitionParsingException: Configuration problem:Unable to locate Spring NamespaceHandler for XML schema namespace
最近由于项目需要,需要jar项目来处理. 我在项目中整合了Spring,在编辑器中启动没有问题,但是使用ant打包为一个完整jar文件,部署后启动报错如下 org.springframework.be ...
- nyoj 96 n-1位数(处理前导 0 的情况)(string)
n-1位数 时间限制:3000 ms | 内存限制:65535 KB 难度:1 描述 已知w是一个大于10但不大于1000000的无符号整数,若w是n(n≥2)位的整数,则 ...
- nyoj 2 括号配对问题(stack)
括号配对问题 时间限制:3000 ms | 内存限制:65535 KB 难度:3 描述 现在,有一行括号序列,请你检查这行括号是否配对. 输入 第一行输入一个数N(0& ...
- JavaEE JDBC RowSet行集
RowSet行集 @author ixenos 应用背景 1.基于结果集的缺点:在与用户的整个交互过程中,必须始终与数据库保持连接 后果:当用户长时间离开时,数据库连接长时间被占用,而这属于稀缺资源: ...
- HDU4463-Outlets,简单最小生成树。1A水过~~
Outlets ...