0

Im making a custom WebClient class with some functionalities that is not available in the WebClient framework class. I actually using this class like this:

using (var client = new CustomWebClient(10000))
{
     client.Tries = 5; //Number of tries that i want to get some page
     GetPage(client);
}

The CustomWebClient class:

 public class CustomWebClient : WebClient
 {
    public CookieContainer Cookies { get; }
    public int Timeout { get; set; }
    public int Tries { get; set; }

    public CustomWebClient () : this(60000)
    {
    }

    public CustomWebClient (int timeOut)
    {
        Timeout = timeOut;
        Cookies = new CookieContainer();
        Encoding = Encoding.UTF8;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
       // some code here, but calling the base method
    }

    //this method actually is important to make the Tries logic.
    protected override WebResponse GetWebResponse(WebRequest request)
    {
        try
        {
            return base.GetWebResponse(request);
        }
        catch (WebException ex)
        {
            if(ex.Status == WebExceptionStatus.Timeout || ex.Status == WebExceptionStatus.ConnectFailure)
            if (--Tries == 0)
                throw;

            GetWebResponse(request);
        }
    }

   }

When the 10000 miliseconds ends, i the base.GetWebResponse(request); throws an WebException with WebExceptionStatus.Timeout status. And the Tries is subtracted. But when i execute the GetWebResponse(request); to retry obtain the response, it dont waits 10000 miliseconds and throws the exception again and it goes on until the 5 tries. How to obtain the response again, making another request?

Thanks.

gog
  • 11,788
  • 23
  • 67
  • 129

1 Answers1

0

As noted in the comments, you're reusing the same WebRequest object. You could clone the WebRequest object using code from this answer and pass the clone to base.GetWebResponse() Something like this:

protected override WebResponse GetWebResponse(WebRequest request)
{
    WebRequest deepCopiedWebRequest = ObjectCopier.Clone<WebRequest>(request);
    try
    {
        return base.GetWebResponse(deepCopiedWebRequest);
    }
    catch (WebException ex)
    {
        if(ex.Status == WebExceptionStatus.Timeout || ex.Status == WebExceptionStatus.ConnectFailure)
        if (--Tries == 0)
            throw;

        GetWebResponse(request);
    }
}
Community
  • 1
  • 1
davehenry
  • 1,026
  • 9
  • 24
  • I just tried that and it says "Type 'System.Net.WebRequest+WebProxyWrapper' is not marked as serializable.". So I don't think this works... – John Apr 13 '18 at 17:44