连接消失时超时。 请帮助我
我想把我的代码暂停一下。 当文件被下载并且我没有上网时,它会计入60秒,如果连接没有返回,则会给出一条消息。
这是代码:
string novoNome; novoNome = strlocal + "\\" + zipNome; using (WebClient wcDownload = new WebClient()) { try { if (!Directory.Exists(strlocal)) { Directory.CreateDirectory(strlocal); } #region comunicação para download //string saida; // cria uma requisição do arquivo para download webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.ReadWriteTimeout = 60000; webResponse = (HttpWebResponse)webRequest.GetResponse(); //Perguntar o tamanho do arquivo Int64 fileSize = webResponse.ContentLength; Uri uri = new Uri(url); // Abrindo arquivo para Download strResponse = wcDownload.OpenRead(uri); // Criando novo arquivo para salvar no HDD strLocal = new FileStream(novoNome, FileMode.Create, FileAccess.Write, FileShare.None); #endregion #region transferencia int bytesSize = 0; byte[] downBuffer = new byte[2048]; try { while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0) { strLocal.Write(downBuffer, 0, bytesSize); //if(this.IsAccessible) this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length, fileSize }); //wcDownload.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wcDownload_DownloadProgressChanged); } } catch (WebException ex) { MessageBox.Show("WEB ERROO:" + ex.Message); } catch (Exception e) { MessageBox.Show("Erro:" + e.Message); } #endregion } catch (WebException ex) { MessageBox.Show("WEB ERROO:" + ex.Message); } catch (Exception e) { MessageBox.Show("Erro:" + e.Message); } finally { strResponse.Close(); strLocal.Close(); } }
抱歉英语不好,我是巴西人。
请帮忙!!
谢谢。
我相信你不需要为此自定义超时处理实现。 尝试将webRequest.Timeout
属性设置为60000。
要指定在读取或写入操作超时之前等待的时间,请使用ReadWriteTimeout属性。
重要
必须在调用GetRequestStream或GetResponse方法之前设置Timeout属性。 调用GetRequestStream或GetResponse方法后更改Timeout属性无效
编辑:
如果您正在寻找自定义超时处理,您仍然可以利用内置的Timeout
。 因此,只需处理WebException
,然后分析exeption Status属性,它可以指示导致超时的原因。 有不同的状态代码可以通过断开网络(模拟网络连接丢失)在本地计算机上模拟它并查看状态,然后您可以添加一些代码来处理这种情况并启动自定义计时器60秒。
我相信你需要处理以下状态:
- ConnectFailure :无法在传输级别联系远程服务点。
- 超时 :在请求超时期间未收到任何响应。
查看所有可用状态: WebExceptionStatus Enumeration
如果您需要更多详细信息或有些不明确的地方,请告诉我。