Answer the question
In order to leave comments, you need to log in
How to limit the number of threads running at the same time?
Good day, comrades.
Got a question. For example, I have 100 defined entities that perform certain actions. I want to run them in a multithread, but so that no more than 15 threads work at the same time, and at the time when a certain entity left the thread (i.e. completed its task), a new one immediately entered this thread.
How to do it (when working with thread)? At first glance, the simplest method is the semaphore. But is it right?
Thank you.
Answer the question
In order to leave comments, you need to log in
The easiest option is to use Parallel.Foreach .
var myEntities = new MyEntity[100];
var maxThreads = 15;
System.Threading.Tasks.Parallel.ForEach(
myEntities,
new System.Threading.Tasks.ParallelOptions { MaxDegreeOfParallelism = maxThreads },
entity =>
{
entity.Do()
});
var myEntities = new MyEntity[100];
var maxThreads = 15;
var semaphoreSlim = new SemaphoreSlim(maxThreads);
var tasks = new List<Task>(myEntities.Length);
foreach (var entity in myEntities)
{
tasks.Add(Task.Run(() =>
{
semaphoreSlim.Wait();
try
{
entity.Do();
}
finally
{
semaphoreSlim.Release();
}
}));
}
Task.WaitAll(tasks.ToArray());
var myEntities = new MyEntity[100];
var maxThreads = 3;
var semaphore = new Semaphore(maxThreads, maxThreads);
var threads = new List<Thread>(myEntities.Length);
foreach (var entity in myEntities)
{
var thread = new Thread(() =>
{
semaphore.WaitOne();
try
{
entity.Do();
}
finally
{
semaphore.Release();
}
});
threads.Add(thread);
thread.Start();
}
foreach (var thread in threads)
thread.Join();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question