I have used Task.WaitAll inside an async method in my HomeController, but it is not waiting to complete execution of the async methods. What did I do wrong here? Instead of waiting, it immediately goes to the next statement.
HomeController.cs:
private List<Task> taskList = new List<Task>();
public ActionResult Index()
{
for (i=0; i<5; i++)
{
SendMessages();
}
Task.WaitAll(taskList.ToArray());
// call demo method
}
private async Task SendMessages()
{
var task = Task.Factory.StartNew(() => ProcessMessages()
taskList.Add(task);
}
private async Task ProcessMessages()
{
while (run for 10 minutes)
{
// data save
}
}
I have added a Task into taskList and used Task.WaitAll(taskList.ToArray()); to wait for all tasks to complete, then call demo method. But instead of waiting and executing the whole loop, it immediately goes down after Task.WaitAll(taskList.ToArray()); and executes call demo method. Why is this?
private List<Task> taskList = new List<Task>();? The current one defined inIndexcannot be accessed to add tasks to bySendMessages. So it looks like you are waiting on an empty list of tasks. Furthermore, you should useawait Task.WhenAllinstead of the blockingWaitAlltaskListit is outside index()run for 10 minuteslogic in ProcessMessages?var startTime = DateTime.UtcNow; while (DateTime.UtcNow - startTime < TimeSpan.FromMinutes(10))while((DateTime.UtcNow - startTime).TotalMinutes < 10). The code that you mentioned is not waiting for 10 minutes and therefore you see that the WaitAll method does not result in 10 minutes wait.