Archeg
Archeg

Reputation: 8462

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

Upvotes: 11

Views: 4617

Answers (3)

Nick Butler
Nick Butler

Reputation: 24403

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()
);

Upvotes: 24

Joel Martinez
Joel Martinez

Reputation: 47789

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

Upvotes: 2

JaredPar
JaredPar

Reputation: 755161

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.

Upvotes: 3

Related Questions