How can I await an array of tasks and stop waiting on first exception?

前端 未结 3 965
一向
一向 2020-12-03 21:49

I have an array of tasks and I am awaiting them with Task.WhenAll. My tasks are failing frequently, in which case I inform the user with a message box so that she can try ag

3条回答
  •  难免孤独
    2020-12-03 22:22

    Your loop waits for each of the tasks in pseudo-serial, so that's why it waits for task1 to complete before checking if task2 failed.

    You might find this article helpful on a pattern for aborting after the first failure: http://gigi.nullneuron.net/gigilabs/patterns-for-asynchronous-composite-tasks-in-c/

        public static async Task WhenAllFailFast(
            params Task[] tasks)
        {
            var taskList = tasks.ToList();
            while (taskList.Count > 0)
            {
                var task = await Task.WhenAny(taskList).ConfigureAwait(false);
                if(task.Exception != null)
                {
                    // Left as an exercise for the reader: 
                    // properly unwrap the AggregateException; 
                    // handle the exception(s);
                    // cancel the other running tasks.
                    throw task.Exception.InnerException;           
                }
    
                taskList.Remove(task);
            }
            return await Task.WhenAll(tasks).ConfigureAwait(false);
         }
    

提交回复
热议问题