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.