I’m executing a query that returns approximately 11,000 rows. Each one of these rows is mapped to a unique POCO that I wrote a lightweight ORM to handle creating, called ToCustomObject<T>
. Right now, I have an already async method that gets the results of this query and puts them into a DataTable
. I then loop through all of the rows and call ToCustomObject
on them to generate my object, and then add it to a List<T>
. The query itself only takes half a second, but the loop to generate all my POCOs takes multiple seconds.
public async Task<List<Foo>> GetFoosAsync()
{
//empty list to populate and return
List<Foo> foos = [];
//example, this is not how the query actually executes, do not need assistance with this part
string query = "select t.Field1, t.Field2 from Table";
DataTable results = await customDbHandlerThatsNotRelevant.ExecuteQueryAsync(query);
//async way to handle this?
foreach (DataRow row in results.Rows)
foos.Add(row.ToCustomObject<Foo>());
return foos ;
}
I had thought about maybe using Task.WhenAll()
to put all the generations into a task list and execute that way, but foos.Add()
is not awaitable. I also looked into Parallel.ForEach()
, but I’m not as familiar with that and from what I could tell, would not accomplish what I’m trying to do.
TL;DR: How can I make all occurrences of foos.Add(row.ToCustomObject<Foo>());
occur asynchronously?