David Rutten
David Rutten

Reputation: 4806

WebClient.DownloadDataAsync SocketException crashing my app

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?

Upvotes: 1

Views: 1096

Answers (2)

Matthew Abbott
Matthew Abbott

Reputation: 61617

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.

Upvotes: 1

jdot
jdot

Reputation: 811

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

Upvotes: 2

Related Questions