c# 任务异常处理

class Program
    {
        public static void Main(string[] args)
        {
            
            string[] urls = new string[]{
                "http://wwww.baidu.coms",
                "http://wwww.baidu.coms",
                "http://wwww.baidu.coms",
                "http://wwww.baidu.coms"
            };
            
            
            List<Task<string>> alltask = new List<Task<string>>();
            
            //任务中没有被处理的异常会被包含在任务中返回;
            alltask = urls.Select(async x=>{
                                      
                                          HttpClient http = new HttpClient();
                                           return await http.GetStringAsync(x);                                  
                                  }).ToList();
        Task<string[]> ttt = null;
        try {
                
            (ttt = Task.WhenAll(alltask)).Wait();
            
        } catch{
            foreach(var t in ttt.Exception.Flatten().InnerExceptions){ //通过聚合异常来记录并行任务抛出的异常
                Console.WriteLine("taskId is {0}, taskExceptionMessage is {1};", ttt.Id, t.Message);
                
            }
            foreach (var tt in alltask) {
                    
                    Console.WriteLine(tt.Exception.InnerException.Message);
                }
        }
            
            Console.ReadKey(true);
        }
    }

 

posted @ 2019-01-02 11:31  我是外婆  阅读(442)  评论(0编辑  收藏  举报