[英]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. 我正在使用Web客户端向服务器发送一些请求参数,然后根据请求获得响应。 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. 但是我每次尝试发送Web客户端请求时都面临的问题是,如果在发送请求时Internet断开连接,它将使我的应用程序挂起。 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. 如果执行该行(如果Internet断开连接),它将挂起应用程序。
You can extend WebClient, so it will have timeout. 您可以扩展WebClient,因此它将超时。 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. 实际上, webclient
默认超时时间是100秒,但默认情况下大约需要20到25或30秒。因此,您可以根据自己的响应(知道服务器要花费多少时间)进行更改。 You can also use threads
for working this code independently your UI
will not Hanged. 您也可以使用threads
独立处理此代码,而UI
不会挂起。
Hope it will help. 希望它会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.