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 WaitWaitAsync, 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的更多相关文章

  1. 【C#】【Thread】Semaphore/SemaphoreSlim信号量

    System.Threading.Semaphore 类表示一个命名(系统范围)信号量或本地信号量. 它是一个对 Win32 信号量对象的精简包装. Win32 信号量是计数信号量,可用于控制对资源池 ...

  2. C#并行编程 (Barrier,CountdownEvent,ManualResetEventSlim,SemaphoreSlim,SpinLock,SpinWait )

    背景 有时候必须访问变量.实例.方法.属性或者结构体,而这些并没有准备好用于并发访问,或者有时候需要执行部分代码,而这些代码必须单独运行,这是不得不通过将任务分解的方式让它们独立运行. 当任务和线程要 ...

  3. 第十三节:实际开发中使用最多的监视锁Monitor、lock语法糖的扩展、混合锁的使用(ManualResetEvent、SemaphoreSlim、ReaderWriterLockSlim)

    一. 监视锁(Monitor和lock) 1. Monitor类,限定线程个数的一把锁,两个核心方法: Enter:锁住某个资源. Exit:退出某一个资源. 测试案例:开启5个线程同时对一个变量进行 ...

  4. C# SemaphoreSlim 实现

    当多个任务或线程并行运行时,难以避免的对某些有限的资源进行并发的访问.可以考虑使用信号量来进行这方面的控制(System.Threading.Semaphore)是表示一个Windows内核的信号量对 ...

  5. 《C#多线程编程实战》2.4 SemaphoreSlim

    这个简单多了. 理解也是很好理解. 比上一个mutex好理解多了. 这个SemaphoreSlim是干什么呢? 就是限制线程的来访问. 好比说一次只有两个,一次只有三个  这样的线程来访问资源. 有点 ...

  6. Semaphore and SemaphoreSlim

    https://msdn.microsoft.com/en-us/library/z6zx288a(v=vs.110).aspx The System.Threading.Semaphore clas ...

  7. 一次 .NET Core 中玩锁的经历:ManualResetEventSlim, Semaphore 与 SemaphoreSlim

    最近同事对  .net core memcached 缓存客户端 EnyimMemcachedCore 进行了高并发下的压力测试,发现在 linux 上高并发下使用 async 异步方法读取缓存数据会 ...

  8. Mutex vs Semaphore vs Monitor vs SemaphoreSlim

    C#开发者(面试者)都会遇到Mutex,Semaphore,Monitor,SemaphoreSlim这四个与锁相关的C#类型,本文期望以最简洁明了的方式阐述四种对象的区别. 线程安全 教条式理解 如 ...

  9. SemaphoreSlim 实现

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/dz45693/article/deta ...

随机推荐

  1. 洛谷——P1731 [NOI1999]生日蛋糕

    P1731 [NOI1999]生日蛋糕 搜索+剪枝 常见的剪枝: 若当前状态+后面所要搜索的最差的状态$>$或是$<$最后的状态,就返回 预处理最差的状态 #include<iost ...

  2. 我能考虑到的数组(老)方法就这些了(es5)

    代码注释都写的很清楚了 关键字:斐波那契数组.二维数组.多维数组(矩阵)... <!DOCTYPE html> <html lang="en"> <h ...

  3. [Python3网络爬虫开发实战] 1.7.1-Charles的安装

    Charles是一个网络抓包工具,相比Fiddler,其功能更为强大,而且跨平台支持得更好,所以这里选用它来作为主要的移动端抓包工具. 1. 相关链接 官方网站:https://www.charles ...

  4. 安装配置Keepalived

    一.在haproxy容器安装Keepalived 1.进入haproxy容器: docker exec -it h1 bash 2.apt-get update(因为haproxy容器为Ubuntu) ...

  5. python3.x Day5 subprocess模块!!

    subprocess模块: # subprocess用来替换多个旧模块和函数 os.system os.spawn* os.popen* popen2.* commands.* subprocess简 ...

  6. 修改 root密码

    sudo su #切换到root账户sudo passwd root  #输入密码

  7. vscode调试nodejs

    1.安装nodejs 2.安装vscode 3.vscode安装debugger for chrome插件 4.新建nodejs-test文件夹,新建server.js空白文件,添加内容: var h ...

  8. [luoguP1328] 生活大爆炸版石头剪刀布(模拟)

    传送门 虽然是模拟,但是我们可以用矩阵保存结果,来是其更加简便. ——代码 #include <cstdio> #include <iostream> ][] = {{, , ...

  9. csu - 1566: The Maze Makers (bfs)

    http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1566 题意还是蛮难懂的,至少对于我来说,需要认真读题. 输入矩阵的每一个数字换成2进制后,顺时针围 ...

  10. POJ 3684_Physics Experiment

    题意: 若干球最初从高到低排列,依次落下. 球与地面碰撞,速度不变方向相反,球之间碰撞, 交换速度和方向.问某一时刻各个球的高度. 分析: 把球之间的碰撞看成是擦肩而过,但是由于半径的存在,最后每个球 ...