简体   繁体   中英

Task Parallel Library exception handling

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?

To clarify, I think the second pattern is the better one but I have a chunk of code which makes use of the first pattern and I am trying to find out if it needs re-factoring ie if it turns out that not all exceptions will be trapped.

The first approach assumes exceptions will be raised for every invocation. While this might be true, the exceptions don't seem "exceptional" and smells of a design issue. If the exceptions are not exceptional, then the result doesn't make much sense. The other problem is that if you do want a "result" (ie something other than Exception ) you can't because the one and only Result slot is used for an Exception . Another problem is that you don't get the re-throwing of the exception back on the main thread (you could do that manually) so you don't get the catch semantics (ie you're using the Handle method).

The second method will be better understood by more people.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM