Reputation: 300
I have a scenario where different code from my application can call the following method
async Task downloadFile(string fileName)
{
await downloadService(fileName);
}
Need a machanism where I can control the max number of requests it can send. For example after 5 active requests I want the rest to be queued up and next will only initiate once we get a response from one of the existing requests. I also need a machanism where I can listen to all the active/queued requests in my code something like Task.WhenAll
I am mostly interested in a built-in .Net library. I know TaskScheduler but seems like I've to implement majority of the Enqueue/Dequeue stuff myself. Wondering if a more suitable library exists.
Upvotes: 2
Views: 415
Reputation: 6374
You can try the SemaphoreSlim class as follows:
SemaphoreSlim semaphore = new SemaphoreSlim(5, 5);
async Task downloadFile(string fileName)
{
await semaphore.WaitAsync();
try
{
await downloadService(fileName);
}
finally
{
semaphore.Release();
}
}
Upvotes: 6