Junior — Middle
How can the number of concurrently running threads in a program be controlled?
sobes.tech AI
Answer from AI
In C#, the Semaphore or SemaphoreSlim class is often used to control the number of concurrently running threads. They allow limiting the number of threads that can execute a certain section of code simultaneously.
Example of using SemaphoreSlim:
using System;
using System.Threading;
class Program
{
static SemaphoreSlim semaphore = new SemaphoreSlim(3); // maximum 3 threads at the same time
static void Worker(int id)
{
semaphore.Wait(); // request permission
Console.WriteLine($"Thread {id} started working");
Thread.Sleep(1000); // simulate work
Console.WriteLine($"Thread {id} finished working");
semaphore.Release(); // release permission
}
static void Main()
{
for (int i = 1; i <= 10; i++)
{
int localId = i;
new Thread(() => Worker(localId)).Start();
}
}
}
In this example, no more than three threads can work simultaneously.