Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I create a global exception handler for winforms app that is making asyncronous WebClient calls
    text
    copied!<p>I have a winforms app that is making asyncronous WebClient calls with a callback procedures as follows...</p> <pre><code>using (var wc = new WebClient()) { wc.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadCompleted); wc.DownloadProgressChanged+=new DownloadProgressChangedEventHandler(DownloadProgressCallback); //other stuff wc.DownloadFileAsync(uri, fullLocalPath); } </code></pre> <p>I want to create a global exception handler so I have defined an application event for it...</p> <pre><code>[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(); } </code></pre> <p>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?</p> <p>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?</p> <p>I am just looking for best practices when using asyncronous callbacks in a winforms app.</p> <p><strong>EDIT</strong></p> <p>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. </p> <p>If it IS non-null...can you tell me how to cause the callback error to bubble up to my global exception handler?</p> <p>I think I would do it like this...</p> <pre><code>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); } </code></pre> <p>Seth</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload