Is there default way to get first task that finished successfully?

前端 未结 4 1449
被撕碎了的回忆
被撕碎了的回忆 2020-12-10 05:37

Lets say that i have a couple of tasks:

void Sample(IEnumerable someInts)
{
    var taskList = someInts.Select(x => DownloadSomeString(x));
}

         


        
4条回答
  •  旧巷少年郎
    2020-12-10 06:37

    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" );
    }
    

提交回复
热议问题