简体   繁体   English

WebClient强制超时

[英]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. 我试图强制超时到5000毫秒,但它不起作用下载不停止或退出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? 我得到一个System.Net.WebException“操作已经超时” - 你绝对不会吞下这个例外吗?

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

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

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