I want await to throw AggregateException, not just the first Exception

前端 未结 4 1308
滥情空心
滥情空心 2020-11-28 09:15

When awaiting a faulted task (one that has an exception set), await will rethrow the stored exception. If the stored exception is an AggregateException

4条回答
  •  眼角桃花
    2020-11-28 10:12

    I know I'm late but i found this neat little trick which does what you want. Since the full set of exceptions are available with on awaited Task, calling this Task's Wait or a .Result will throw an aggregate exception.

        static void Main(string[] args)
        {
            var task = Run();
            task.Wait();
        }
        public static async Task Run()
        {
    
            Task[] tasks = new[] { CreateTask("ex1"), CreateTask("ex2") };
            var compositeTask = Task.WhenAll(tasks);
            try
            {
                await compositeTask.ContinueWith((antecedant) => { }, TaskContinuationOptions.ExecuteSynchronously);
                compositeTask.Wait();
            }
            catch (AggregateException aex)
            {
                foreach (var ex in aex.InnerExceptions)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
    
        static Task CreateTask(string message)
        {
            return Task.Factory.StartNew(() => { throw new Exception(message); });
        }
    

提交回复
热议问题