Reputation: 33
I want to limit the maximum number of threads. How can I do it? I know I could use something like SetMaximum
...if I were using the ThreadPool
.
public async Task ProcessAsync()
{
while (true)
{
Task.Run(Work);
}
}
async Task Work()
{
// some time-consuming job
}
Upvotes: 1
Views: 1576
Reputation: 16126
You can use a SemaphoreSlim to limit the number of concurrent threads. For example to limit the execution to 3 threads at a time:
async Task Main()
{
SemaphoreSlim semaphore = new SemaphoreSlim(3); // Limit to 3 threads
while (true)
{
await semaphore.WaitAsync(); // Wait when more than 3 threads are running
Task.Run(() =>
{
Work();
semaphore.Release(); // Work is done, signal to semaphore that more work is possible
});
}
}
void Work()
{
Console.WriteLine(DateTime.Now);
Thread.Sleep(3000);
}
Semaphores can be used to limit the consumption of many types of resources, but in this example the resource is a thread from the thread pool.
Upvotes: 3