简体   繁体   中英

WebClient force Timeout

    public class MyWebClient : WebClient {

        private int timeout;
        public int Timeout
        {
            get
            {
                return timeout;
            }
            set
            {
                timeout = value;
            }
        }

        public MyWebClient()
        {
            this.timeout = 5000;
        }

        public MyWebClient(int timeout)
        {
            this.timeout = timeout;
        }

        protected override WebRequest GetWebRequest(Uri address)
        {
            var result = base.GetWebRequest(address);
            result.Timeout = this.timeout;
            return result;
        } 
}

I am trying to force timeout to 5000 milliseconds, but it is not working the download does not stop or exit after 5000 milsecs.

It can be done by Task timeout, but i don't want to use Task here.

any alternative way to do it??

Can you give any more information? What are you trying to download from, and are you certain it's not working?

I've tried your code and it seems to work fine; I get a System.Net.WebException "The operation has timed out" - you're definitely not swallowing this exception?

你可以把请求放在一个新的线程上,然后观察那个线程,如果你达到你指定的超时,那么杀死线程,从而中止请求。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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