我正在创建一个自定义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);
会WebException
WebExceptionStatus.Timeout
状态。减去了试验。但是当我执行GetWebResponse(request);
重试获得响应时,它不会等待10000毫秒并再次抛出异常并继续直到5次尝试。如何再次获得响应,再提出请求?
感谢。
答案 0 :(得分:0)
如评论中所述,您重复使用相同的WebRequest对象。您可以使用this answer中的代码克隆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);
}
}