I'll start on my previous problem: I was using WebClient.DownloadData to download binary data. But, in some cases, the download was too long (not the request-response, mostly because of the streaming). You can read about this problem here.
So, as a workaround, I started using the WebClient.DownloadDataAsync:
try
{
using (WebClient wc = new WebClient())
{
byte[] content = null;
wc.DownloadDataCompleted +=
delegate(object sender, DownloadDataCompletedEventArgs e)
{
if (e.Error != null)
{
content = null;
}
else if (!e.Cancelled)
{
content = e.Result;
}
((AutoResetEvent)e.UserState).Set();
};
AutoResetEvent downloadWaitEvent = new AutoResetEvent(false);
wc.DownloadDataAsync(@"\\1.1.1\a.jpg", downloadWaitEvent);
if (downloadWaitEvent.WaitOne(Timeout))
{
return content;
}
else
{
wc.CancelAsync();
}
}
}
catch (Exception ex)
{
// I don't catch the web exception here
}
It works great, until I receive unhandled WebException, with the following scenario:
My timeout is set to 10 seconds. When the reset event fails, I call wc.CancelAsync(), which terminate the download process. After few more seconds, I receive an unhandled web exception that says "The network path was not found", that is called from System.Net.FileWebRequest.GetResponseCallback.
I know I can catch this one in the AppDomain.HandleUnhandledException, but is there more elegant way to catch this error?
Thanks