Question

I have the following code... On the first iteration, it queries the server just fine. But if get an error, return action() gets called but nothing happens on Fiddler and immediately jumps to the catch block. What is happening?

for (int retry = 0; retry < retryCount; retry++)
{
    try
    {
        return action();
    }
    catch (WebException ex)
    {
        // truncated for clarity
    }
}

It's called Retry.Do(() => HttpReturnJson(request), TimeSpan.FromSeconds(15), 3);

This is what my HttpReturnJson looks like:

EDITED I tried enclosing WebResponse and StreamReader inside using blocks... It doesn't seem to be that the old WebResponse response is getting disposed. On the retry, I'm still reading from the old one. How do I resend the request on the retry?

public string HttpReturnJson(HttpWebRequest request)
{
    using (WebResponse response = request.GetResponse())
    using (var stream = response.GetResponseStream())
    using (StreamReader reader = new StreamReader(stream))
    {
        string data = reader.ReadToEnd();
        return data;
    }
}

Source of this code: Cleanest way to write retry logic?

Was it helpful?

Solution

You can't read same response more than once, so you need to re-send request on every retry and than read from the response.

Below is how your HttpReturnJson could look like for re-creating request (assuming just regular GET on known url):

public string HttpReturnJson(string url)
{
    using (var request = WebRequest.Create(url))
    using (WebResponse response = request.GetResponse())
    using (var stream = response.GetResponseStream())
    using (StreamReader reader = new StreamReader(stream))
    {
        string data = reader.ReadToEnd();
        return data;
    }
}

Note that if you need headers/post data you'll need to set those up too on every request.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top