c# semaphoreSlim限制线程数

前言

我们在使用线程的时候,如果多个线程数去访问一个资源的时候,那么是非常影响程序的运行的,因为如果有写的操作,那么需要写锁,那么线程都会堵在同一个地方,那么我们可以限制一下访问一个资源的线程数。

正文

static SemaphoreSlim _semaphore = new SemaphoreSlim(4);
static object x = new object();
static int y = 0;
static void Main(string[] args)
{
	for (int i = 0; i <= 100; i++)

	{
		string ThreadName = "Thread" + i;
		int secondsToWait = 2;
		var t = new Thread(() => AccessDataBase(ThreadName, secondsToWait));
		// t.IsBackground = true;
		t.Start();
	}
}

static void AccessDataBase(string name, int seconds)
{
	Console.WriteLine($"{name }waits to access a database");
	_semaphore.Wait();
	lock (x)
	{
		y++;
	}
	Console.WriteLine("现在的正在执行的线程数为:" + y);
	Console.WriteLine($"{name} was grants an access to a database");
	Thread.Sleep(TimeSpan.FromSeconds(seconds));
	lock (x)
	{
		y--;
	}
	_semaphore.Release();

	Console.WriteLine($"{name} was completed");
}

在上面代码中,我创建了100个线程,然而正在执行的线程数一直只有4个。

这样我们就限制线程访问资源的频率,为什么我在_semaphore.Wait();里面还是加了lock呢?因为并发数依然为4。

posted @ 2020-07-01 16:58  敖毛毛  阅读(583)  评论(0编辑  收藏  举报