Based on some questions on SO, mainly this one: Throttling asynchronous tasks
I have implemented the SemaphoreSlim object to concurrently processes requests over a range of methods in my application. Most of these methods are taking in lists of IDs and getting single byte arrays back per ID in a concurrent fashion from the web. The implementation looks like this:
using (var semaphore = new SemaphoreSlim(MaxConcurrency))
{
var tasks = fileMetadata.GroupBy(x => x.StorageType).Select(async storageTypeFileMetadata=>
{
await semaphore.WaitAsync();
try
{
var fileManager = FileManagerFactory.CreateFileManager((StorageType)storageTypeFileMetadata.Key);
await fileManager.UpdateFilesAsync(storageTypeFileMetadata);
}
finally
{
semaphore.Release();
}
});
await Task.WhenAll(tasks);
}
Is there a way to abstract out a method or some reusable code snippet for the semaphore code, and pass in the work I need done, so it can be reused without re-writing the semaphore code each time? The only difference amongst multiple methods using this same semaphore pattern is the list I am iterating and the work it is doing in the try{}.
I am thinking something like pass list.select(x=> my task method with my work in it) to a semaphore method which is all the wrapper semaphore code.