Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling exception with TPL without Wait()

I have an application with Start and Stop buttons, and a thread that is ran in the background after pressing Start. I use MVC and TPL for that.

How can I handle exception in the TPL, as I never invoke Wait() method? On any exception I need to show Error message box, and this box should be shown after it was thrown right away.

I have always single thread in the background, so you cannot press Start without previously Stopping the thread.

I'm looking for some good patterns or best practice. I have an idea to place try..catch inside thread, and invoke an event on each catch, but I'm not sure is such approach is good architecture decision

like image 815
Archeg Avatar asked Jan 03 '12 15:01

Archeg


3 Answers

If you're using Tasks, you can add a continuation that only runs if an exception is thrown. You can also tell it to run on your UI thread so you can use your UI controls:

task.ContinueWith(
    t => { var x = t.Exception; ...handle exception... },
    CancellationToken.None,
    TaskContinuationOptions.OnlyOnFaulted,
    TaskScheduler.FromCurrentSynchronizationContext()
);
like image 105
Nick Butler Avatar answered Nov 05 '22 07:11

Nick Butler


At a high level the Wait method simply takes the Exception which occurred in the background thread, wraps it in another Exception type and rethrows it. So you can observe the original Exception on the background thread with a standard try / catch block surrounding your logic code.

like image 38
JaredPar Avatar answered Nov 05 '22 07:11

JaredPar


There's nothing wrong with handling the exception right in the Task (on the background thread). If you need to show UI in the event of an exception, you can use the Dispatcher (assuming you're using wpf or silverlight): http://msdn.microsoft.com/en-us/magazine/cc163328.aspx

like image 2
Joel Martinez Avatar answered Nov 05 '22 07:11

Joel Martinez