Tobey60
Tobey60

Reputation: 147

Problem with Task.WhenAll How can I find out if each task was completed?

I only want to set AllMethodsCompleted = true if all the tasks in TasksList were completed successfully. But I get an error message when I want to find out if everything was completed successfully. What am I doing wrong?

Error CS0029: Cannot implicitly convert type 'void' to 'System.Threading.Tasks.Task'

public async Task PlayerAccountDetails()
{
    var playerCountryData = GetPlayerCountryData();
    var playerTagsData = GetPlayerTagsData();
    var TasksList = new List<Task> { playerCountryData, playerTagsData };

    Task t = await Task.WhenAll(TasksList);
    if (t.Status == TaskStatus.RanToCompletion)
        AllMethodsCompleted = true;
    else
        AllMethodsCompleted = false;
}

Upvotes: 3

Views: 1428

Answers (2)

Johnathan Barclay
Johnathan Barclay

Reputation: 20363

Task.WhenAll(IEnumerable<Task>) returns Task.

By awaiting a (non-generic) Task you get no return value, hence why Task t = await Task.WhenAll(TasksList); won't compile. You simply need:

await Task.WhenAll(TasksList);

You could also write this as:

Task t = Task.WhenAll(TasksList);
await t;

Upvotes: 2

Sean
Sean

Reputation: 62472

Task.WhenAll will return a task that you can wait on for all the tasks to completion, so you just need to say:

public async Task PlayerAccountDetails()
{
    var playerCountryData = GetPlayerCountryData();
    var playerTagsData = GetPlayerTagsData();
    var TasksList = new List<Task> { playerCountryData, playerTagsData };

    await Task.WhenAll(TasksList);
    AllMethodsCompleted = true;
}

If any of the tasks were cancelled or threw an exception then the line await Task.WhenAll(TasksList) will throw an exception.

If you want to handle the failure of one of the tasks then you can do this:

try
{
    await Task.WhenAll(TasksList);
    AllMethodsCompleted = true;
}
catch
{
    AllMethodsCompleted = false;
}

Upvotes: 3

Related Questions