Reputation: 16219
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?
Upvotes: 1
Views: 8476
Reputation: 54887
Task.Factory.StartNew
should not be used to launch asynchronous operations, since it does not unwrap the returned Task
, and instead returns a new Task
that completes as soon as the asynchronous operation launches (or, more precisely, completes its synchronous part). You should use Task.Run
instead.
Additionally, SendMessages
should not be async. However, Index
should be, allowing you to use the asynchronous WhenAll
instead of the blocking WaitAll
.
private List<Task> taskList = new List<Task>();
public async Task<ActionResult> Index()
{
for (i = 0; i < 5; i++)
{
SendMessages();
}
await Task.WhenAll(taskList);
// call demo method
}
private void SendMessages()
{
var task = Task.Run(() => ProcessMessagesAsync()); // here
taskList.Add(task);
}
private async Task ProcessMessagesAsync()
{
while (run for 10 minutes)
{
// data save
}
}
Upvotes: 2