Task의 특수 예외 처리:AggregateException

//AggregateException:       ,  Task       ,                 
static void Method11()
{
    var task = Task.Factory.StartNew(() =>
    {
        var childTask1 = Task.Factory.StartNew(() =>
        {
            //                ,       ....

            //        
            throw new Exception("my god!Exception from childTask1 happend!");
        }, TaskCreationOptions.AttachedToParent);

        var childTask2 = Task.Factory.StartNew(() =>
        {
            throw new Exception("my god!Exception from childTask2 happend!");
        }, TaskCreationOptions.AttachedToParent);
    });
    try
    {
        try
        {
            task.Wait();   //1.       
        }
        catch (AggregateException ex)  //2.      
        {
            foreach (var item in ex.InnerExceptions)
            {
                Console.WriteLine(item.InnerException.Message + "     " + item.GetType().Name);
            }

            //3.    ,       ,    Handle      
            ex.Handle(p =>
            {
                if (p.InnerException.Message == "my god!Exception from childTask1 happend!")
                    return true;
                else
                    return false; //  false          
            });
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("-----------------------------------------------------");
        Console.WriteLine(ex.InnerException.InnerException.Message);
    }
}

좋은 웹페이지 즐겨찾기