C#多线程编程笔记-使用SemaphoreSlim类

近来在学习Eugene Agafonov编写的《C#多线程编程实战》(译),做些笔记也顺便分享一下^-^

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

using System;
using System.Threading;

namespace semaphoreSlim_Test
{
    class Program
    {
        static void Main(string[] args)
        {
            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();
            }

            Console.ReadKey();
        }

        static SemaphoreSlim _semaphor = new SemaphoreSlim(4);

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

程序运行结果如下


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

每个线程都尝试获取数据库的访问,但我们借助于信号系统限制了访问数据库的并发线程最多为4个。所以当有4个线程获取了数据库的访问时,其余线程需等待,直到之前线程中的某一个完成工作并调用_semaphor.Release()方法来发出信号。

猜你喜欢

转载自blog.csdn.net/qq_35445058/article/details/80731248