繁体   English   中英

如何重试收到超时异常的Web客户端请求

[英]How to retry a webclient request that gets timeout exception

我正在制作具有某些功能的自定义WebClient类,而这些功能在WebClient框架类中不可用。 我实际上像这样使用此类:

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

CustomWebClient类:

 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);
        }
    }

   }

当10000毫秒结束时, base.GetWebResponse(request); 抛出状态为WebExceptionWebExceptionStatus.Timeout 并减去Tries。 但是当我执行GetWebResponse(request); 要重试以获得响应,它不会等待10000毫秒,然后再次引发异常,直到5次尝试为止。 如何再次获得响应,提出另一个请求?

谢谢。

如评论中所述,您正在重用相同的WebRequest对象。 您可以使用答案中的代码克隆WebRequest对象,然后将克隆传递给base.GetWebResponse()类似:

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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM