I am trying to just download html from a webpage, but I want to give it up after 10 seconds. The code below loads the text just fine, but it can take longer than 10 seconds. I have a timeout set, but StreamReading takes a lot of time. What is the best way to stop further processing after 10 seconds when closing connections?
I get a WebException if req.GetResponse () takes more than 10 seconds, but reading wr.GetResponseStream () is something that takes time. I also want all connections to be properly closed.
the code:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Timeout = 10000;
req.ReadWriteTimeout = 10000;
using (WebResponse wr = req.GetResponse())
{
Console.WriteLine("A: " + DateTime.Now.ToString(" HH:mm:ss:fff"));
using (StreamReader sr = new StreamReader(wr.GetResponseStream(), true))
{
Console.WriteLine("B: " + DateTime.Now.ToString(" HH:mm:ss:fff"));
var b = sr.ReadToEnd();
Console.WriteLine("C: " + DateTime.Now.ToString(" HH:mm:ss:fff"));
}
}
Output Example:
A: 20:04:36:522
B: 20:04:36:522
C: 20:04:54:337
Elapsed Time: ~18 Seconds
source
share