WebClient timeout problem
I read that WebClient doesn't support timeout but I find smth strange. My WebClient 开发者_如何学Cclass:
class MyWebClient : WebClient
{
private int timeout;
public int Timeout
{
get { return timeout; }
set { timeout = value; }
}
public MyWebClient()
{
timeout = 5000;
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request.GetType() == typeof(HttpWebRequest))
{
((HttpWebRequest)request).Timeout = timeout;
}
Console.WriteLine("timeout {0}", request.Timeout);
return request;
}
}
When I make request this prints:
timeout 10000when I comment
//((HttpWebRequest)request).Timeout = timeout;
it prints:
timeout 100000it is ok default value
but when I set:
((HttpWebRequest)request).Timeout = 5000;
it prints:
timeout 5000and timouts works
Can anybody explain why I must enter the timeout value directly?
The WebRequest
will not know what timeout you want to use unless you set it.
Perhaps you are confusing the setting of your class's local field timeout
with setting the Timeout
property on the WebRequest
class? Or is it that you expect WebClient
to have a Timeout
property and to set this the request timeout automatically for you?
Unless you only want to set your own timeout for HTTP requests, the whole checking of the request type is unnecessary as Timeout
is part of the WebRequest
base class and so is available without a cast to HttpWebRequest
.
精彩评论