开发者

WebClient timeout problem

开发者 https://www.devze.com 2023-02-21 01:46 出处:网络
I read that WebClient doesn\'t support timeout but I find smth strange. My WebClient 开发者_如何学Cclass:

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 10000

when I comment

//((HttpWebRequest)request).Timeout = timeout;

it prints:

timeout 100000

it is ok default value

but when I set:

((HttpWebRequest)request).Timeout = 5000;

it prints:

timeout 5000

and 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消