C# SemophoreSlim

它是Semaphore的轻量级版本,主要是针对本地资源的访问;
信号量有两种类型:本地信号量和已经命名的系统信号量,前者是针对本地的应用程序,后者显示在整个操作系统也使用于进程间的同步;
SemaphoreSlim轻量级取代Semaphore,而不使用windows内核信号量的类,它不支持已命名的系统命名信号量;故而其作为单个应用程序中进行同步的建议信号量;
其用法和Semaphore差不多;可以在其构造函数中指定输入信号量的线程初始数量,以及进入信号量的最大线程数;(具体可参见MSDN)
下面直接上代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace Chapter02_SemaphoreSlim
{
    class Program
    {
        static void Main(string[] args)
        {
            for(int i=1; i<=6; i++)
            {
                string ThreadName = "Thread" + i;
                int SecondToWait = 2 + 2 * i;
                var t = new Thread(() => AccessDataBase(ThreadName, SecondToWait));
                t.Start();

            }
        }

        static SemaphoreSlim _semophore = new SemaphoreSlim(4);

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

        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值