I have tried to simulate a scenario that when I request my api service once, I have to do 4 IO bounded request to different external API's or databases etc. to get response on my example.
I want to start these requests at the same time as asynchronously and If I get negative response (null for my example) one of these requests, stop all request as soon as I get negative response one of them.
According to my example, the requests was started at the same time and even if I get negative response one of requests I have to wait until long request(task4) finishes. It means I was able to get result at least in 40 second. How can I stop working unnecessarily 20 second more, when I get null response from second request (task2) on 20th second?
If It's possible how I should handle this scenario?
public class HomeController : Controller
{
public async Task<string> SampleAsyncAction()
{
var task1 = DoSomeIOAsync(10000);
var task2 = DoSomeIOAsync(20000);
var task3 = DoSomeIOAsync(30000);
var task4 = DoSomeIOAsync(40000);
var result = await Task.WhenAll(task1, task2, task3, task4);
if (result.Any(x=> x == null))
return "Error occurred";
return "Operation was done successfully in " + result.Sum().ToString() + "millisecond";
}
private int? DoSomeIO(int millisecond)
{
Thread.Sleep(millisecond);
if (millisecond == 20000)
return null;
return (millisecond);
}
private async Task<int?> DoSomeIOAsync(int millisecond)
{
return await Task.Run(() => DoSomeIO(millisecond));
}
}