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. HTML 之 DOM文件对象模型

    文件对象模型 (DOM: Document Object Model) DOM 是 W3C定义的一种访问文档的标准. "The W3C Document Object Model (DOM) ...

  2. 关于Integer,127和128的问题

    里面的,直接贴源码来看 Integer i=127; Integer b=128; Integer c=128; Integer d=127;Integer j;System.out.println( ...

  3. 基于PHP的微信支付教程

    微信支付作为各大移动支付方式之一,本课程只要向大家介绍并使用微信支付的常用功能,进而集合到已有的项目中去,希望各位能够快速上手并掌握实战"干货". 出处至:汇智网  hubwiz. ...

  4. AndroidSweetSheet:从底部弹出面板(1)

     AndroidSweetSheet:从底部弹出面板(1) AndroidSweetSheet又是一个从底部弹出面板的开源项目.我在以前写的文章中介绍了不少这些项目,见附录文章5,6,7,8.现在 ...

  5. 在ubuntu 18.04下装有线守护wg

    wg你懂的是什么,下面讲讲我这段时间安装过程,发觉这个软件和CENTOS 7下面不是很合拍,它更适合ubuntu,因为ubuntu仍然用iptables,而CENTOS 早就用了firewalld了, ...

  6. poj1984并查集的相对偏移

    #include<stdio.h>//典型题 #include<math.h> #define N 40010 struct node { int x,y,z; }pre[N] ...

  7. Python模块基础

    概念: 在Python中,一个.py文件就称之为一个模块(Module) 好处: 1. 提高可维护性 2. 可重用 3. 避免函数名.变量名冲突. 每个模块有独立的命名空间,因此相同名字的函数和变量完 ...

  8. [K/3Cloud] 调用其他界面时通过Session传递对象参数

    DynamicFormShowParameter参数的CustomParams参数列表只支持string类型的参数,对于复杂参数的传递需要通过单据View对象的共享Session来完成,如: 在调用界 ...

  9. 洛谷P2888 [USACO07NOV]牛栏Cow Hurdles

    题目描述 Farmer John wants the cows to prepare for the county jumping competition, so Bessie and the gan ...

  10. [NOIP2004] 提高组 洛谷P1091 合唱队形

    题目描述 N位同学站成一排,音乐老师要请其中的(N-K)位同学出列,使得剩下的K位同学排成合唱队形. 合唱队形是指这样的一种队形:设K位同学从左到右依次编号为1,2…,K,他们的身高分别为T1,T2, ...