Exception Handling
If there was an exception thrown by the worker delegate, the exception is passed to the completion callback.
The completion callback will be called on the thread on which the async worker was started if this thread supports synchronization (UI thread do support synchronization). Otherwise, it will be called on the worker thread.
Failing Operation with no Completion Handler
If the operation throws an exception and there is no completion handler set then the global handler for unhandled exceptions is notified:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // first we need to register for unhandled exceptions AppDomain.CurrentDomain.UnhandledException += (s, e) => { // handle the unhandled exception }; DoWorkEventHandler worker = delegate { throw new InvalidOperationException( "test" ); }; AsyncWorker asyncWorker = new AsyncWorker(worker); asyncWorker.RunWorkerAsync(); |
Failing Operation with Completion Handler
If the operation throws an exception and there is a completion handler set then the completion handler is responsible to handle the exception. The global handler for unhandled exceptions will not be notified:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | DoWorkEventHandler worker = delegate { throw new InvalidOperationException(); }; RunWorkerCompletedEventHandler completed = delegate ( object sender, RunWorkerCompletedEventArgs e) { // handle the exception (null if no exception) Exception exception = e.Error; }; AsyncWorker asyncWorker= new AsyncWorker(worker, completed); asyncWorker.RunWorkerAsync(); |