I'm trying to use Task.WaitAll
on a list of tasks. The thing is the tasks are an async lambda which breaks Tasks.WaitAll
as it never waits.
Here is an example code block:
List<Task> tasks = new List<Task>();
tasks.Add(Task.Factory.StartNew(async () =>
{
using (dbContext = new DatabaseContext())
{
var records = await dbContext.Where(r => r.Id = 100).ToListAsync();
//do long cpu process here...
}
}
Task.WaitAll(tasks);
//do more stuff here
This doesn't wait because of the async lambda. So how am I supposed to await I/O operations in my lambda?
Task.Factory.StartNew
doesn't recogniseasync
delegates as there is no overload that accepts a function returning aTask
.This plus other reasons (see StartNew is dangerous) is why you should be using
Task.Run
here: