简体   繁体   中英

Web client request gets hanged if Internet is disconnected while executing it using

I am using web client to send some request parameters to server and then get response according to request. But the issue which i face when every i try to send web client request is if Internet gets disconnected while sending request, it will hang my application. Sometimes it crashes the application. My code snippet is give below.

 WebClient webClient=new WebClient()
  userData = webClient.UploadValues(URL, "POST", parameters);

                       `

While executing that line if Internet disconnects it hangs the application.

You can extend WebClient, so it will have timeout. Try this:

class WebClientWithTimeout : WebClient {
  public WebClientWithTimeout(int timeout) {
    _timeout = timeout
  }
  // Timeout in seconds
  int _timeout;
  protected override WebRequest GetWebRequest(Uri uri) {
    WebRequest webRequest = base.GetWebRequest(uri);
    webRequest.Timeout = 1000 * _timeout;
    return w;
  }
}
 private class YourWebClient : WebClient
        {
            protected override WebRequest GetWebRequest(Uri uri)
            {
                WebRequest wr = base.GetWebRequest(uri);
                wr.Timeout = 7 * 1000;
                return wr;
            }
        }

You can change your timeout accordingly to your desire. I have tested it and it worked for me. Actually webclient default timeout is 100 sec but it takes about 20 to 25 or 30 sec in default.So you change it according to your responce that you know how much time it takes from your server. You can also use threads for working this code independently your UI will not Hanged.

Hope it will help.

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