Task Parallel Library exception handling

Posted by user1680766 on Stack Overflow See other posts from Stack Overflow or by user1680766
Published on 2012-09-18T20:08:40Z Indexed on 2012/09/20 9:38 UTC
Read the original article Hit count: 155

Filed under:
|

When handling exceptions in TPL tasks I have come across two ways to handle exceptions. The first catches the exception within the task and returns it within the result like so:

                            var task = Task<Exception>.Factory.StartNew(
                                () =>
                                    {
                                        try
                                        {
                                            // Do Something

                                            return null;
                                        }
                                        catch (System.Exception e)
                                        {
                                            return e;
                                        }
                                    });

                            task.ContinueWith(
                                r =>
                                    {
                                        if (r.Result != null)
                                        {
                                            // Handle Exception
                                        }
                                    });

The second is the one shown within the documentation and I guess the proper way to do things:

                                var task = Task.Factory.StartNew(
                                    () =>
                                        {
                                            // Do Something
                                        });
                                task.ContinueWith(
                                    r =>
                                        {
                                            if (r.Exception != null)
                                            {
                                                // Handle Aggregate Exception
                                                r.Exception.Handle(y => true);
                                            }
                                        });

I am wondering if there is anything wrong with the first approach? I have received 'unhandled aggregate exception' exceptions every now and again using this technique and was wondering how this can happen?

© Stack Overflow or respective owner

Related posts about c#

Related posts about task-parallel-library