5

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 i.e. if it turns out that not all exceptions will be trapped.

4

1 回答 1

3

第一种方法假定每次调用都会引发异常。虽然这可能是真的,但这些异常似乎并不“异常”,而且有设计问题的味道。如果异常不是异常,那么结果就没有多大意义。另一个问题是,如果你确实想要一个“结果”(即,除了 之外的东西Exception)你不能因为唯一的Result插槽用于Exception. 另一个问题是您没有在主线程上重新抛出异常(您可以手动执行此操作),因此您没有获得 catch 语义(即您正在使用该Handle方法)。

第二种方法会被更多人更好地理解。

于 2012-09-20T13:06:17.787 回答