近来在学习Eugene Agafonov编写的《C#多线程编程实战》(译),做些笔记也顺便分享一下^-^
SemaphoreSlim是Semaphore的轻量级版本,该类限制了同时访问同一个资源的线程数量
using System;
using System.Threading;
namespace semaphoreSlim_Test
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 6; i++)
{
string threadName = "Thread" + i;
int secondsToWait = 2 + 2 * i;
var t = new Thread(() => AccessDatabase(threadName, secondsToWait));
t.Start();
}
Console.ReadKey();
}
static SemaphoreSlim _semaphor = new SemaphoreSlim(4);
static void AccessDatabase(string name,int seconds)
{
Console.WriteLi