twaldron twaldron - 1 month ago 18
C# Question

Catching Error when using Task.Factory

i am using the following

Task.Factory.StartNew(() => DoPrintConfigPage(serial));


then the function i am calling looks like this

private void DoPrintConfigPage(string serial)
{
//do printing work
}


My problem is an exception is being thrown inside the thread and not being handled.

I have tried wrapping it in a try catch

try
{
Task.Factory.StartNew(() => DoPrintConfigPage(serial));
}
catch (Exception ex) { }


but it still is not catching the error and thus crashing the application.

How can I catch exceptions in the main thread so I can handle them?

Update



I have made the changes recommended below and still it is saying the exception is unhandled

var task = Task.Factory.StartNew(() => DoPrintConfigPage(serial))
.ContinueWith(tsk =>
{
MessageBox.Show("something broke");
},TaskContinuationOptions.OnlyOnFaulted);


then in my
DoConfigPage
I added another try catch.

In this catch is now where it is crashing and saying the exception being thrown was unhandled, what am I missing?

private void DoPrintConfigPage(string serial)
{
try
{
//call the print function
}
catch (Exception ex)
{
throw ex; //it is crashing here and saying it is unhandled
}
}


I also tried what Eric J. suggested with the same results

var task = Task.Factory.StartNew(() => DoPrintConfigPage(serial));

try
{
task.Wait();
}
catch (AggregateException ex) { MessageBox.Show("something broke"); }

Answer

Alternatively, you can chain your task creation and add a ContinueWith:

var job = Task.Factory
    .StartNew(...)
    .ContinueWith(tsk => 
         {
              // check tsk for exception and handle
         });

EDIT: This snippet, when run, pops up the message box for me:

void Main()
{
    var serial = "some serial";
    var task =  Task.Factory
        .StartNew(() => DoPrintConfigPage(serial))
        .ContinueWith(tsk =>
        {
            MessageBox.Show("something broke");
            var flattened = tsk.Exception.Flatten();

            // NOTE: Don't actually handle exceptions this way, m'kay?
            flattened.Handle(ex => { MessageBox.Show("Error:" + ex.Message); return true;});
        },TaskContinuationOptions.OnlyOnFaulted);

}

public void DoPrintConfigPage(string serial)
{
    throw new Exception("BOOM!");
}