0

I've been going at this all day. I am creating web requests using

public async static Task<string> FetchString(string Url)
{
    HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(Url);
    Request.Proxy = null;
    WebResponse Response = await Request.GetResponseAsync();
    Stream DataStream = Response.GetResponseStream();
    if (DataStream == null) return String.Empty;
    StreamReader DataReader = new StreamReader(DataStream);
    return await DataReader.ReadToEndAsync();
}

which works great. The problem is, though, is that sometimes it hangs on HTTP 504, gateway timeout. Using Request.Timeout (or any of the three variants) does not time the method out for when my method hangs on 504 (edit: timeout doesn't reply to async methods, great). To combat this, I've tried to create a timer that would kill the thread the request was running on, but had no luck doing that, though it felt like a working concept.

How would I be able to asynchronously get the contents of a URL in string form, while still being abe to time the request out after say five seconds?

Scarsz
  • 13
  • 1
  • 9
  • If you can't get HttpClient to behave the way you want (likely case as you went with WebReqest instead) there is always `WhenAny`: http://stackoverflow.com/questions/4238345/asynchronously-wait-for-taskt-to-complete-with-timeout – Alexei Levenkov Oct 30 '15 at 06:24
  • @AlexeiLevenkov I'm not sure how I'd implement that but I understand what that's explaining. :/ – Scarsz Oct 30 '15 at 17:30

1 Answers1

0

In my research, I found this is a duplicate question (sorry, i dunno how this works)

Timeout behaviour in HttpWebRequest.GetResponse() vs GetResponseAsync()

Timeout does not apply to asynchronous HttpWebRequest requests. To quote the docs:

The Timeout property has no effect on asynchronous requests

I recommend you use HttpClient instead, which was designed with asynchronous requests in mind. -Stephen Cleary

Community
  • 1
  • 1
Patrick
  • 1,089
  • 14
  • 17
  • Self-answering is ok (and you did it properly), also for duplicate you should be able to "flag" question as duplicate. I've closed it as duplicate, feel free to eventually accept your answer (or delete - whatever you like). – Alexei Levenkov Oct 30 '15 at 17:54
  • THanks for that - I wasn't the OP though. – Patrick Nov 01 '15 at 23:04