信号量类使您可以限制可以访问关键节的线程数。该类用于控制对资源池的访问。System.Threading.Semaphore是Semaphore的命名空间,因为它具有实现Semaphore所需的所有方法和属性。
为了在C#中使用信号量,您只需要实例化一个信号量对象的实例。它至少有两个参数-
-
MSDN
| 序号 | 构造函数与说明 | 
|---|---|
| 1 | Semaphore(Int32,Int32) 初始化Semaphore类的新实例,指定条目的初始数量和并发条目的最大数量。 | 
| 2 | Semaphore(Int32,Int32,String)- 初始化Semaphore类的新实例,指定条目的初始数量和并发条目的最大数量,并可选地指定系统信号对象的名称。 | 
| 3 | Semaphore(Int32,Int32,String,Boolean) 初始化Semaphore类的新实例,指定条目的初始数量和并发条目的最大数量,还可以选择指定系统信号对象的名称,并指定接收以下内容的变量:指示是否创建新系统信号的值。 | 
现在让我们看一个例子:
在这里,我们使用了以下Semaphore构造函数,该构造函数初始化Semaphore类的新实例,指定并发条目的最大数量,并可以选择保留一些条目。
static Semaphore semaphore = new Semaphore(2, 2);
using System;
using System.Threading;
namespace Program
{
class Demo
   {
      static Thread[] t = new Thread[5];
      static Semaphore semaphore = new Semaphore(2, 2);
      static void DoSomething()      {
         Console.WriteLine("{0} = waiting", Thread.CurrentThread.Name);
         semaphore.WaitOne();
         Console.WriteLine("{0} begins!", Thread.CurrentThread.Name);
         Thread.Sleep(1000);
         Console.WriteLine("{0} releasing...", Thread.CurrentThread.Name);
         semaphore.Release();
      }
      static void Main(string[] args)
      {
         for (int j = 0; j < 5; j++)
         {
            t[j] = new Thread(DoSomething);
            t[j].Name = "thread number " + j;
            t[j].Start();
         }
         Console.Read();
      }
   }
}输出结果
以下是输出
thread number 2 = waiting thread number 0 = waiting thread number 3 = waiting thread number 1 = waiting thread number 4 = waiting thread number 2 begins! thread number 1 begins! thread number 2 releasing... thread number 1 releasing... thread number 4 begins! thread number 3 begins! thread number 4 releasing... thread number 0 begins! thread number 3 releasing... thread number 0 releasing...