开发者

WebClient.DownloadDataAsync SocketException crashing my app

开发者 https://www.devze.com 2023-01-07 06:27 出处:网络
I\'ve got the following code to download a binary file from the web: WebClient client = new WebClient();

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开发者_StackOverflow社区 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?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消