Proper way of handling exception in task continuewith

后端 未结 6 1579
悲&欢浪女
悲&欢浪女 2020-12-07 22:06

Please have a look at the following code-

static void Main(string[] args)
{
    // Get the task.
    var task = Task.Factory.StartNew(() => { r         


        
6条回答
  •  孤城傲影
    2020-12-07 22:49

    What you have there is an AggregateException. This is thrown from tasks and requires you to check the inner exceptions to find specific ones. Like this:

    task.ContinueWith(t =>
    {
        if (t.Exception is AggregateException) // is it an AggregateException?
        {
            var ae = t.Exception as AggregateException;
    
            foreach (var e in ae.InnerExceptions) // loop them and print their messages
            {
                Console.WriteLine(e.Message); // output is "y" .. because that's what you threw
            }
        }
    },
    TaskContinuationOptions.OnlyOnFaulted);
    

提交回复
热议问题