tags:

views:

21

answers:

1

Is it possible to throw an Exception from the Completed event of an Async action?

My situation is that I'm using a WebClient class and executing an async download. If an error is encountered then I can retrieve this via the AsyncCompletedEventArgs of the WebClient.DownloadFileCompleted event.

However what I really want to do, is then throw this Exception further up the stack to other areas of code that are waiting for this download to complete, so the means of reporting the error back to the user does not have to be managed down at a low level.

Does anyone know if/how to do this? As currently I get an UnhandledException because the event is obviously called from External code.

+2  A: 

If you are using async, then the other code normally isn't actively (or even passively) waiting for completion. The callback happens on a separate thread, so no; you can't really raise an error and have it interrupt your main thread(s).

You would need to set a flag that something bad happened (perhaps including the exception instance) - and let the other code query it when it chooses (although you might touch a gate/mutex/monitor to help notify the other thread). This approach is done in part by the BackgroundWorker approach, where the originating thread (when notified) can pick up the exception.

Marc Gravell
Thanks Marc. This is the method I've adopted in the end.
Ian