Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to catch when any Task terminates due exception and log?

Is it possible to catch when any Task terminates due exception and log? I've added CurrentDomain_UnhandledException handling but this doesn't help.

I create tasks using Task.Factory.StartNew() as usual. When somewhere inside such task exception occurs it crashes silently (but it supposed to work forever, i'm also using LongRunning option). So I want to be notified about such behavior.

Ideallly I want to set some option somewhere to be notified when any Task crashes due exception.

If it is not possible then likely I should add something to each Task I create? Of course I can just add big try{} finally{} block inside each Task, but probably there are better solutions?

like image 936
Oleg Vazhnev Avatar asked Nov 13 '12 09:11

Oleg Vazhnev


1 Answers

Assuming you have a Test as Task to run:

static int Test()
{
    throw new Exception();
}
  1. First Approach - Process exception in the caller's thread:

    Task<int> task = new Task<int>(Test);
    task.Start();
    
    try
    {
        task.Wait();
    }
    catch (AggregateException ex)
    {
        Console.WriteLine(ex);
    }
    

    Note: The exception will be of type AggregateException. All actual exceptions are available through ex.InnerExceptions property.

  2. Second Approach - Process exception in some task's thread:

    Define the ExceptionHandler this way:

    static void ExceptionHandler(Task<int> task)
    {
        var ex = task.Exception;
        Console.WriteLine(ex);
    }
    

    Usage:

    Task<int> task = new Task<int>(Test);
    task.ContinueWith(ExceptionHandler, TaskContinuationOptions.OnlyOnFaulted);
    task.Start();
    

Reference: How to: Handle Exceptions Thrown by Tasks

like image 85
Furqan Safdar Avatar answered Oct 06 '22 01:10

Furqan Safdar