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
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()
);
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With