Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to catch exception in Task?

With System.Threading.Tasks.Task<TResult>, I have to manage the exceptions that could be thrown. I'm looking for the best way to do that. So far, I've created a base class that manages all the uncaught exceptions inside the call of .ContinueWith(...)

I'm wondering if there's a better way do do that. Or even if it is a good way to do that.

public class BaseClass
{
    protected void ExecuteIfTaskIsNotFaulted<T>(Task<T> e, Action action)
    {
        if (!e.IsFaulted) { action(); }
        else
        {
            Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
            {
                /* I display a window explaining the error in the GUI 
                 * and I log the error.
                 */
                this.Handle.Error(e.Exception);
            }));            
        }
    }
}   

public class ChildClass : BaseClass
{
    public void DoItInAThread()
    {
        var context = TaskScheduler.FromCurrentSynchronizationContext();
        Task.Factory.StartNew<StateObject>(() => this.Action())
                    .ContinueWith(e => this.ContinuedAction(e), context);
    }

    private void ContinuedAction(Task<StateObject> e)
    {
        this.ExecuteIfTaskIsNotFaulted(e, () =>
        {
            /* The action to execute 
             * I do stuff with e.Result
             */

        });        
    }
}
like image 619
JiBéDoublevé Avatar asked Oct 19 '12 18:10

JiBéDoublevé


People also ask

What are the 2 ways I can handle exception?

Java provides two different options to handle an exception. You can either use the try-catch-finally approach to handle all kinds of exceptions. Or you can use the try-with-resource approach which allows an easier cleanup process for resources.

How do you capture an exception?

Place any code statements that might raise or throw an exception in a try block, and place statements used to handle the exception or exceptions in one or more catch blocks below the try block. Each catch block includes the exception type and can contain additional statements needed to handle that exception type.

Where should you catch exceptions?

You should catch the exception when you are in the method that knows what to do. For example, forget about how it actually works for the moment, let's say you are writing a library for opening and reading files. Here, the programmer knows what to do, so they catch the exception and handle it.


2 Answers

There are two ways you can do this, dependent on the version of the language you are using.

C# 5.0 and above

You can use the async and await keywords to simplify a great deal of this for you.

async and await were introduced into the language to simplify using the Task Parallel Library, preventing you from having to use ContinueWith and allowing you to continue to program in a top-down manner.

Because of this, you can simply use a try/catch block to catch the exception, like so:

try
{
    // Start the task.
    var task = Task.Factory.StartNew<StateObject>(() => { /* action */ });

    // Await the task.
    await task;
}
catch (Exception e)
{
    // Perform cleanup here.
}

Note that the method encapsulating the above must use have the async keyword applied so you can use await.

C# 4.0 and below

You can handle exceptions using the ContinueWith overload that takes a value from the TaskContinuationOptions enumeration, like so:

// Get the task.
var task = Task.Factory.StartNew<StateObject>(() => { /* action */ });

// For error handling.
task.ContinueWith(t => { /* error handling */ }, context,
    TaskContinuationOptions.OnlyOnFaulted);

The OnlyOnFaulted member of the TaskContinuationOptions enumeration indicates that the continuation should only be executed if the antecedent task threw an exception.

Of course, you can have more than one call to ContinueWith off the same antecedent, handling the non-exceptional case:

// Get the task.
var task = new Task<StateObject>(() => { /* action */ });

// For error handling.
task.ContinueWith(t => { /* error handling */ }, context, 
    TaskContinuationOptions.OnlyOnFaulted);

// If it succeeded.
task.ContinueWith(t => { /* on success */ }, context,
    TaskContinuationOptions.OnlyOnRanToCompletion);

// Run task.
task.Start();
like image 57
casperOne Avatar answered Oct 16 '22 19:10

casperOne


You can create some custom Task factory, which will produce Tasks with exception handling processing embedded. Something like this:

using System;
using System.Threading.Tasks;

class FaFTaskFactory
{
    public static Task StartNew(Action action)
    {
        return Task.Factory.StartNew(action).ContinueWith(
            c =>
            {
                AggregateException exception = c.Exception;

                // Your Exception Handling Code
            },
            TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously
        ).ContinueWith(
            c =>
            {
                // Your task accomplishing Code
            },
            TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously
        );
    }

    public static Task StartNew(Action action, Action<Task> exception_handler, Action<Task> completion_handler)
    {
        return Task.Factory.StartNew(action).ContinueWith(
            exception_handler,
            TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously
        ).ContinueWith(
            completion_handler,
            TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously
        );
    }
};

You can forget about exceptions processing for Tasks produced from this factory in your client code. In the same time you still can wait finishing of such Tasks or use them in Fire-and-Forget style:

var task1 = FaFTaskFactory.StartNew( () => { throw new NullReferenceException(); } );
var task2 = FaFTaskFactory.StartNew( () => { throw new NullReferenceException(); },
                                      c => {    Console.WriteLine("Exception!"); },
                                      c => {    Console.WriteLine("Success!"  ); } );

task1.Wait(); // You can omit this
task2.Wait(); // You can omit this

But if be honest I'm not really sure why you want to have completion handling code. In any case this decision depends on the logic of your application.

like image 20
ZarathustrA Avatar answered Oct 16 '22 17:10

ZarathustrA