Lets say that i have a couple of tasks:
void Sample(IEnumerable someInts)
{
var taskList = someInts.Select(x => DownloadSomeString(x));
}
As a straight forward solution is to wait for any task, check if it is in RanToCompletion state and if not, wait again for any task except the already finished one.
async Task WaitForFirstCompleted( IEnumerable> tasks )
{
var taskList = new List>( tasks );
while ( taskList.Count > 0 )
{
Task firstCompleted = await Task.WhenAny( taskList ).ConfigureAwait(false);
if ( firstCompleted.Status == TaskStatus.RanToCompletion )
{
return firstCompleted.Result;
}
taskList.Remove( firstCompleted );
}
throw new InvalidOperationException( "No task completed successful" );
}