I need to process a bunch of completed orders (thousands). To make it faster, I'm using a SemaphoreSlim
to schedule a number of orders to be processed in parallel. Every order goes through multiple web service calls to various APIs (SOAP, REST). Then I need to take the returned data and process it into a PDF. Here is what I am doing currently (note that this is in an ASP.NET app):
private async Task ProcessOrders(List<Orders> orders)
{
var allTasks = new List<Task>();
var throttler = new SemaphoreSlim(initialCount: 5);
foreach (var order in orders.Where(x => !x.HasError))
{
// do an async wait until we can schedule again
await throttler.WaitAsync();
// using Task.Run() to run the lambda in its own parallel
// flow on the thread pool
allTasks.Add(Task.Run(async () =>
{
try
{
// Call external web service here
// Build order report PDF here
}
finally
{
throttler.Release();
}
}));
}
await Task.WhenAll(allTasks);
}
However, I'm new to TPL and I don't know if this is the right way to do something like this. If it's relevant, this app is hosted on Amazon's AWS cloud.