Proper way of handling exception in task continuewith

后端 未结 6 1582
悲&欢浪女
悲&欢浪女 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 23:01

            try
            {
                var t1 = Task.Delay(1000);
    
                var t2 = t1.ContinueWith(t =>
                {
                    Console.WriteLine("task 2");
                    throw new Exception("task 2 error");
                }, TaskContinuationOptions.OnlyOnRanToCompletion);
    
                var t3 = t2.ContinueWith(_ =>
                {
                    Console.WriteLine("task 3");
                    return Task.Delay(1000);
                }, TaskContinuationOptions.OnlyOnRanToCompletion).Unwrap();
    
                // The key is to await for all tasks rather than just
                // the first or last task.
                await Task.WhenAll(t1, t2, t3);
            }
            catch (AggregateException aex)
            {
                aex.Flatten().Handle(ex =>
                    {
                        // handle your exceptions here
                        Console.WriteLine(ex.Message);
                        return true;
                    });
            }
    

提交回复
热议问题