网络客户端重试 [英] WebClient Retry
本文介绍了网络客户端重试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以重试网络客户端请求?在奇怪的情况下,我的应用程序在尝试连接到 xml web 服务时会抛出错误,但如果我重试,它可以正常工作.我希望它在抛出错误之前重试 2 次,除非有人有更好的解决方案:)
Is it possible to retry a webclient request? On the odd occasion my application will throw an error when attempting to connect to an xml web service but if I retry, it works OK. I'd like it to retry 2 times before throwing an error unless someone has a better solution :)
private void ApplicationBarLogin_Click(object sender, EventArgs e)
{
settings.UsernameSetting = Username.Text;
if (RememberPassword.IsChecked == true)
{
settings.PasswordSetting = Password.Password;
settings.RememberPasswordSetting = true;
}
else
{
settings.RememberPasswordSetting = false;
}
WebClient internode = new WebClient();
internode.Credentials = new NetworkCredential(settings.UsernameSetting, settings.PasswordSetting);
internode.DownloadStringCompleted += new DownloadStringCompletedEventHandler(internode_DownloadStringCompleted);
internode.DownloadStringAsync(new Uri("https://customer-webtools-api.internode.on.net/api/v1.5/"));
}
public void internode_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
else
{
MessageBox.Show("Authentication successfull.");
}
}
推荐答案
如果失败,可以重新发出请求.通过计算重新发出请求的次数,您可以确定何时向用户显示错误.这是对您的代码的快速修改,以展示我的意思.
If you get a failure, you could re-issue the request. By keeping count of the number of times you re-issue the request you can determine when to show the user an error. Here is a quick modification to your code to demonstrate what I mean.
private void ApplicationBarLogin_Click(object sender, EventArgs e)
{
settings.UsernameSetting = Username.Text;
if (RememberPassword.IsChecked == true)
{
settings.PasswordSetting = Password.Password;
settings.RememberPasswordSetting = true;
}
else
{
settings.RememberPasswordSetting = false;
}
WebClient internode = new WebClient();
internode.Credentials = new NetworkCredential(settings.UsernameSetting, settings.PasswordSetting);
internode.DownloadStringCompleted += new DownloadStringCompletedEventHandler(internode_DownloadStringCompleted);
internode.DownloadStringAsync(new Uri("https://customer-webtools-api.internode.on.net/api/v1.5/"));
}
private int _retryCount = 0;
public void internode_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
_retryCount++;
if (_retryCount < 3)
{
WebClient internode = (WebClient)sender;
internode.DownloadStringAsync(new Uri("https://customer-webtools-api.internode.on.net/api/v1.5/"));
}
else
{
_retryCount = 0;
MessageBox.Show(e.Error.Message);
}
}
else
{
_retryCount = 0;
MessageBox.Show("Authentication successfull.");
}
}
这篇关于网络客户端重试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文