This does not wait due to asynchronous lambda. So, how should I wait for I / O operations in my lambda?
The reason Task.WaitAll does not wait for the IO represented by your asynchronous lambda to complete, because Task.Factory.StartNew actually returns a Task<Task> . Since your list is a List<Task> (and Task<T> comes from Task ), you expect from an external task starting with StartNew , and ignoring the internal one created by the asynchronous lambda. That's why they say that Task.Factory.StartNew is dangerous in relation to async.
How could you fix this? You can explicitly call Task<Task>.Unwrap() to get the internal task:
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();
Or, as others have said, you can call Task.Run instead:
tasks.Add(Task.Run(async () => );
Also, since you want to do everything right, you need to use Task.WhenAll , which is why it is required asynchronously, instead of Task.WaitAll , which synchronously blocks:
await Task.WhenAll(tasks);
Yuval Itzchakov
source share