I have a winforms app that is making asyncronous WebClient calls with a callback procedures as follows…
using (var wc = new WebClient())
{
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadCompleted);
wc.DownloadProgressChanged+=new DownloadProgressChangedEventHandler(DownloadProgressCallback);
//other stuff
wc.DownloadFileAsync(uri, fullLocalPath);
}
I want to create a global exception handler so I have defined an application event for it…
[STAThread]
static void Main()
{
Application.ThreadException += new ThreadExceptionEventHandler(ApplicationThreadException);
//other stuff
Application.Exit();
}
private static void ApplicationThreadException(object sender, ThreadExceptionEventArgs e)
{
// Do logging or whatever here
Application.Exit();
}
I believe that I am correct that application errors that are raised by the Callback event will not be caught by the Application.ThreadException? So what is the best way of insuring that the callback exceptions are handled?
I have seen on other SO posts that you can also create a handler for AppDomain.CurrentDomain.UnhandledException. Is that the best way to handle the callback exceptions?
I am just looking for best practices when using asyncronous callbacks in a winforms app.
EDIT
Nicholas…thanks for your answer. So can I put the whole callback into a try catch and then do a throw in the catch. Or do I have to explicitly check the AsyncCompletedEventArgs.error property for a non-null value.
If it IS non-null…can you tell me how to cause the callback error to bubble up to my global exception handler?
I think I would do it like this…
private void DownloadCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
throw e.Error;
}
if (DownloadHasCompleted == null) return;
File.Copy(this.RemoteIniFilePath, this.CurrentIniFilePath, true);
DownloadHasCompleted(this, e);
}
Seth
Any exception will be passed to your
DownloadFileCompletedevent handler.This is called with a AsyncCompletedEventArgs object which has an
Errorproperty.You just need to check this property in your handler – it won’t be an “unhandled exception”.