Suppose I have several tasks:
void Sample(IEnumerable<int> someInts) { var taskList = someInts.Select(x => DownloadSomeString(x)); } async Task<string> DownloadSomeString(int x) {...}
I want to get the result of the first successful task. So the main solution is to write something like:
var taskList = someInts.Select(x => DownloadSomeString(x)); string content = string.Empty; Task<string> firstOne = null; while (string.IsNullOrWhiteSpace(content)){ try { firstOne = await Task.WhenAny(taskList); if (firstOne.Status != TaskStatus.RanToCompletion) { taskList = taskList.Where(x => x != firstOne); continue; } content = await firstOne; } catch(...){taskList = taskList.Where(x => x != firstOne);} }
But this solution seems to run N + ( N -1) + .. + K tasks. Where N someInts.Count and K is the position of the first successful task in tasks, since it restarts all tasks except one that is captured by WhenAny. So, is there a way to get the first task that successfully completed the execution of N tasks? (if the successful task is the last)
source share