Here's what I ended up doing.
I realized that the problem was, I needed simply to cancel WebClient.DownloadString()
when it reached the specified timeout. Since I haven't found anything that would help me in WebClient
, I simply called WebClient.DownloadStringTaskAsync()
. This way, I could use Task.WaitAll
with timeout to wait for WebClient
to finish downloading string and then check if the task has finished (to rule out timeout).
Here's the code:
public string GetHtml(string url)
{
var html = "";
using (var client = new WebClient())
{
// Assign all the important stuff
client.Proxy = this.Proxy;
client.Headers[HttpRequestHeader.UserAgent] = this.UserAgent;
// Run DownloadString() as a task.
var task = client.DownloadStringTaskAsync(url);
// Wait for the task to finish, or timeout
Task.WaitAll(new Task<string>[] { task }, this.Timeout);
// If timeout was reached, cancel task and throw an exception.
if (task.IsCompleted == false)
{
client.CancelAsync();
throw new TimeoutException();
}
// Otherwise, happy. :)
html = task.Result;
}