JAVA和Nginx 教程大全

网站首页 > 精选教程 正文

并发编程 C#- (3) SemaphoreSlim-信号量

wys521 2024-11-06 20:34:27 精选教程 27 ℃ 0 评论

功能:

用来限制能同时访问共享资源的线程上限,避免对有限资源进行超过共享资源的并发访问

特征:

1.如果预计等待的时间较短,可以考虑使用SemaphoreSlim,它则带来的开销更小

2.如果需要有跨进程或AppDomain的同步时,可以考虑使用Semaphore。Semaphore是取得的Windows 内核的信号量,所以在整个系统中是有效的。它主要的接口是Release和WaitOne,使用的方式和SemaphoreSlim是一致的。

3.java.Semaphore一样的效果

4.这个东东仅仅适合单机,不适合分布式

语法:

SemaphoreSlim(int initialCount)


实际使用:比如控制数据库连接池数量

 #region 模板入口
/// <summary>
/// 最大允许上限4个数据库连接
/// </summary>
static SemaphoreSlim _semaphore = new SemaphoreSlim(4);
/// <summary>
/// do other...
/// </summary>
private void Main()
{
   //TemplateThread mthrd2 = new TemplateThread("DecThread thread (减少线程)", 5, new ShareRes.DelegateLog(PrintLog));
   for (int i = 1; i <= 6; i++)
   {
         string threadName = "Thread " + i;
         int secondsToWait = 2;
         var t = new Thread(() => AccessDatabase(threadName, secondsToWait));
         t.Start();
            }
  }
void AccessDatabase(string name, int seconds)
{
   PrintLog("{0} waits to access a database", name);
   _semaphore.Wait();
   PrintLog("{0} was granted an access to a database", name);
   Thread.Sleep(TimeSpan.FromSeconds(seconds));
    PrintLog("{0} is completed", name);
    _semaphore.Release();
}
#endregion

运行效果:


分析:同时运行了6个线程,SemaphoreSlim设置并发上限为4,在58:10秒的开始请求访问数据库连接,允许四个线程thread1,thread2,thread3,thread5获得了访问授权,2秒之后访问结束,thread4,thread6才获得访问授权,java里面对应之的语法Semaphore一样的功能。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表