Check status of async tasks status and get their results

Viewed 683

I'm new to C#. I want to start 4 PostAsync without wait for response, and then check if any of them is completed and HTTP response contain a specific word then cancel other async tasks.

And if a completed PostAsync does not contain the word or is failed, run another task so that total of all async tasks stay at 4

private async void Button_Click(object sender, RoutedEventArgs e)
{
    List<Task> tasks = new List<Task>();
    for (int ctr = 0; ctr <= 2; ctr++)
    {
        tasks.Add(Web("https://google.com/api/", da));
    }
    
    var index = Task.WhenAny(tasks).Result;
}

public static async Task<string> Web(string url, string da)
{
     var response = await client.PostAsync(url,
         new StringContent(da, Encoding.UTF8, "application/json"));

     return response.Content.ReadAsStringAsync().Result; ;
}

I tested above code but don't know how to get the result of completed task, nor add another task in case of failure.

1 Answers

WhenAny will return the first completed task. not an integer. for getting the result you can await the same.

   var completedTask = Task.WhenAny(tasks);

   var result =await completedTask;

do not use task.result ever as it will block the executions.

WhenAny provides an option to asyncrnously iterate through the list of tasks. you can add /remove the tasks to list directly inside the iteration loop. (for cancellation need to pass the same cancellation token for all tasks)

Related