C#使用Semaphore来同步线程
2017-01-11 11:11:00      个评论    来源：Yy

```// 初始化一个信号量，初始值为0，最大值为1.
private Semaphore sem = new Semaphore(0, 1);

private void ReleaseSem()
{
// 释放一个信号量
if (有人在等待)
{
sem.Release();
}
else
{
这个是原来的某个超时的返回的结果。
}
}

public void WaitSem()
{
// 这个函数同时，只能被一个线程调用，避免messageId被覆盖。
lock();

// 等待一个信号，最长等待5秒钟
sem.WaitOne(5000);

unlock();
}```

## 线程池例子

```using System;

public class Fibonacci
{
private int _n;
private int _fibOfN;
private ManualResetEvent _doneEvent;

public int N { get { return _n; } }
public int FibOfN { get { return _fibOfN; } }

// Constructor.
public Fibonacci(int n, ManualResetEvent doneEvent)
{
_n = n;
_doneEvent = doneEvent;
}

// Wrapper method for use with thread pool.
{
_fibOfN = Calculate(_n);
_doneEvent.Set();
}

// Recursive method that calculates the Nth Fibonacci number.
public int Calculate(int n)
{
if (n <= 1)
{
return n;
}

return Calculate(n - 1) + Calculate(n - 2);
}
}

{
static void Main()
{
const int FibonacciCalculations = 10;

// One event is used for each Fibonacci object.
ManualResetEvent[] doneEvents = new ManualResetEvent[FibonacciCalculations];
Fibonacci[] fibArray = new Fibonacci[FibonacciCalculations];
Random r = new Random();

for (int i = 0; i < FibonacciCalculations; i++)
{
doneEvents[i] = new ManualResetEvent(false);
Fibonacci f = new Fibonacci(r.Next(20, 40), doneEvents[i]);
fibArray[i] = f;
}

// Wait for all threads in pool to calculate.
WaitHandle.WaitAll(doneEvents);
Console.WriteLine("All calculations are complete.");

// Display the results.
for (int i= 0; i<FibonacciCalculations; i++)
{
Fibonacci f = fibArray[i];
Console.WriteLine("Fibonacci({0}) = {1}", f.N, f.FibOfN);
}
}
}```

```launching 10 tasks...
All calculations are complete.
Fibonacci(38) = 39088169
Fibonacci(29) = 514229
Fibonacci(25) = 75025
Fibonacci(22) = 17711
Fibonacci(38) = 39088169
Fibonacci(29) = 514229
Fibonacci(29) = 514229
Fibonacci(38) = 39088169
Fibonacci(21) = 10946
Fibonacci(27) = 196418```