Ignore the Tasks throwing Exceptions at Task.WhenAll and get only the completed results

后端 未结 3 1490
遥遥无期
遥遥无期 2021-02-19 01:17

I am working on a Task parallel problem that I have many Tasks that may or may not throw Exception.

I want to process all the tasks that finishes properly and log the re

3条回答
  •  天命终不由人
    2021-02-19 01:44

    You can add HOC with exception handling and then check success.

     class Program
    {
        static async Task Main(string[] args)
        {
            var itemsToProcess = new[] { "one", "two" };
            var results = itemsToProcess.ToDictionary(x => x, async (item) =>
            {
                try
                {
                    var result = await DoAsync();
                    return ((Exception)null, result);
                }
                catch (Exception ex)
                {
                    return (ex, (object)null);
                }
            });
    
            await Task.WhenAll(results.Values);
    
            foreach(var item in results)
            {
                Console.WriteLine(item.Key + (await item.Value).Item1 != null ? " Failed" : "Succeed");
            }
        }
    
        public static async Task DoAsync()
        {
            await Task.Delay(10);
            throw new InvalidOperationException();
        }
    }
    
        

    提交回复
    热议问题