I am trying to download multiple webpages using the WebClient class. When I try to download a website's html, a TargetInvocationException is thrown, and I do not know why it happens. Here is my code:
public HashSet<string> DownloadWebpages(HashSet<string> urls)
{
HashSet<string> HTML = new HashSet<string>();
for (int i = 0; i < urls.Count; i++)
{
WebClient client = new WebClient();
client.DownloadStringCompleted += (s, e) =>
{
try
{
lock (HTML)
{
HTML.Add(e.Result); //The exception happens on this line
}
}
catch { }
};
client.DownloadStringAsync(new Uri(urls.ElementAt(i)));
}
return HTML;
}
Is there any way to fix this. All I'm trying to do is download multiple webpages using async, trying to make it has fast as possible.
async/awaitand DownloadStringTaskAsync at least. Even better, use HttpClient insteadcatch { }doesn't bode well. Why are you swallowing exceptions without any kind of logging? What is the detail of the exception? Please show the complete stack trace, including inner exceptions.