views:

14

answers:

2

I've got the following code to download a binary file from the web:

WebClient client = new WebClient();
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadDataCompleted);
client.DownloadDataAsync(uri);

All works well until the connection is severed. If I disable my wireless, the app crashes out:

System::Windows::Forms::Application::ThreadException event occured
SENDER: System.Threading.Thread
EXCEPTION: System.Net.Sockets.SocketException
MESSAGE: A socket operation was attempted to an unreachable network 74.200.243.250:80
SOURCE: System
CALL STACK
  at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
  at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)

How do I catch this exception, or, since it's on it's own thread, how do I stop it from crashing my app?

+1  A: 

In your DownloadDataCompleted method, check the argument's Error property. This gets populated if there's an exception during the async operation. Handle the exception appropriately in this method.

It's similar to a BackgroundWorker's RunWorkerCompleted.

http://msdn.microsoft.com/en-us/library/system.componentmodel.asynccompletedeventargs.error.aspx

jdot
Hah, that was a lot easier than I thought.
David Rutten
+1  A: 

I'm not sure why it is crashing your application. The DownloadDataCompletedEventArgs has an Error property which is the exception that was thrown during the async operation.

Matthew Abbott