This is mostly comment to D Stanley's answer - switching to parallel/async code unlikely to improve performance.
If your main concern is responsiveness/scalability - async would be better as generally DB access is IO-bound operation. It also allows to pick between sequential and parallel processing (i.e. in case your DB layer does not support concurrent requests on same connection for some reason). Additionally with async
it is easier to get synchronization right for updating UI/request if you use default synchronization context.
Sequential: it will run about as long as non-async solution, but the thread will be free to perform other activities at the same time (for UI applications like WinForms/WPF) or process requests (ASP.Net).
async public Task<ResultType> CallMethodAsync()
{
foreach(var obj in input)
{
var singleResult = await CallDatabaseAsync(obj);
// combine results if needed
}
// return combined results
}
Parallel: will run all requests at the same time, will likely be faster than sequential solution.
async public Task<ResultType> CallMethodAsync()
{
List<Task<SingleResultType>> tasks = new List<Task<SingleResultType>>();
foreach(var obj in input)
{
tasks.Add(await CallDatabaseAsync(obj));
}
await Task.WhenAll(tasks);
foreach(SingleResultType result in tasks.Select(t=>t.Result))
{
// combine results if needed
}
// return combined results
}
Note that async
generally requires all your code to be asynchronous - so if you converting just small piece of code to run in parallel Parallel.ForEach
may be easier solution as it does not involve dealing with await vs Task.Wait - Deadlock?.