Multi-threaded programming Learning Series --SemaphoreSlim class

Sample Code

//设置同时访问线程最大数量
static SemaphoreSlim _semaphore = new SemaphoreSlim(4);

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

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

Results: The
Here Insert Picture Description
principle
new SemaphoreSlim an object, set the maximum number of threads to access the 4, 5 open thread, found a thread starts 5 has been in a waiting state until the thread 1 is complete, call _semaphore.Release () release, the thread 5 to execute the code behind.

Published 37 original articles · won praise 3 · Views 6330

Guess you like

Origin blog.csdn.net/huan13479195089/article/details/88947313