title: Catching execeptions using Async programming
body: <p>VS C# 2005</p>
  
  <p>I am using the code below to upload a file Async using the web client. However, I am not sure that I can catch the exception if there is a problem. Because the <code>wc.UpLoadFileAsync</code> would return immediately. So it seems pointless to put the <code>try...catch</code> in there.</p>
  
  <p>So to test, I deliberately created an error to see what would happen if I put in an incorrect URL. However, I get this in my debug output window.</p>
  
  <pre><code>A first chance exception of type 'System.Net.WebException' occurred in System.dll
  File completed
  </code></pre>
  
  <p>So it doesn't fire in the <code>try...catch</code>. And it still fires the <code>UploadFileCompleted</code> method</p>
  
  <pre><code>private void upload_config_to_server()
  {
      Uri url = new Uri("http://10.10.10.3/softphone/config.xml");
  
      WebClient wc = new WebClient();
      if (!wc.IsBusy)
      {
          wc.UploadProgressChanged += new UploadProgressChangedEventHandler(wc_UploadProgressChanged);
          wc.UploadFileCompleted += new UploadFileCompletedEventHandler(wc_UploadFileCompleted);      
  
          try
          {
              wc.UploadFileAsync(url, "PUT", "config.xml");
          }
          catch (WebException webex)
          {
              Console.WriteLine("Web Exception {0}", webex.Message);
          }
          catch (Exception ex)
          {
              Console.WriteLine("Exception {0}", ex.Message);
          }
      }
  }
  
  private void wc_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
  {
      Console.WriteLine("Bytes uploaded {0}", e.BytesSent);
  }
  
  private void wc_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
  {
      Console.WriteLine("File completed");
  }  
  </code></pre>
  
  <p>Is there a correct way to handle this. I just want to show a message box to the user to display the reason why the upload file failed. However, as the uploaded file can be big it could take several seconds to upload it. So I need to have the Async to prevent the UI freezing up.</p>
  
  <p>Many thanks for any suggestion,</p>