C# SemophoreSlim

来源:互联网 发布:键盘弹钢琴软件下载 编辑:程序博客网 时间:2024/05/01 21:41

它是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