Reputation: 7890
I have this class that Inheritance WebClient
:
public class WebDownload : WebClient
{
/// <summary>
/// Time in milliseconds
/// </summary>
public int Timeout { get; set; }
public WebDownload() : this(10000) { }
public WebDownload(int timeout)
{
this.Timeout = timeout;
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
if (request != null)
{
request.Timeout = this.Timeout;
}
return request;
}
}
And in my code i loop over a lot of Urls
and download the one after one with :
string source;
using (WebDownload client = new WebDownload()) // WebClient class inherits IDisposable
{
client.Headers.Add("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:26.0) Gecko/20100101 Firefox/26.0");
source = client.DownloadString(url);
}
return source;
And i have a problem that sometimes the code stuck on this method:
source = client.DownloadString(url);
Any idea why it happen? I put a Timeout
of 10 seconds to stop the request if it fails.
Upvotes: 1
Views: 2071
Reputation: 16401
If your DownloadString is getting stuck, please have a try with DownloadStringAsync
.
Long running operations should run asynchronously.
WebClient w = new WebClient();
w.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler(downloadCompleted);
w.DownloadStringAsync(new Uri("http://stackoverflow.com"));
in this example, the custom method downloadCompleted happens when download is finished, you will have the downloaded string available in the Result
property.
You can use CancelAsync
to cancel asynchronous operations if needed.
Upvotes: 1