码迷,mamicode.com
首页 > 编程语言 > 详细

线程-使用SimaphoreSlim类

时间:2018-07-03 21:39:07      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:数据库   write   thread   grant   main方法   信号   access   res   ++   

SimaphoreSlim类是作为Semaphore类的轻量级版本的。该类限制了同时访问同一个资源的线程数量。

代码Demo:

using System;
using System.Threading;

在Main方法下面加入以下代码片段:

 static SemaphoreSlim _semaphore = new SemaphoreSlim(4);------1

static void AccessDatabase(string name, int seconds)
{
Console.WriteLine("{0} waits to access a database", name);
_semaphore.Wait();
Console.WriteLine("{0} was granted an access to a database", name);
Thread.Sleep(TimeSpan.FromSeconds(seconds));
Console.WriteLine("{0} is completed", name);
_semaphore.Release();
}

在Main方法中加入以下代码片段:

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();
}

工作原理:

主线程启动时,创建了SemaphoreSlim的一个实例,并在其构造函数中制定允许的并发线程数量(1行所示)。然后启动了6个不同名称和不同初始运动时间的线程。

每个线程都尝试获取数据库的访问,但是我们借助于信号系统限制了访问数据库的并发数为4个线程。当有4个线程获取了数据库的访问后,其它两个线程需要等待,知道之前线程中的某一个完成工作并调用_semaphore.Release方法来发出信号。

线程-使用SimaphoreSlim类

标签:数据库   write   thread   grant   main方法   信号   access   res   ++   

原文地址:https://www.cnblogs.com/v-haoz/p/9260521.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!