如果我的代码在 C# 中连接 Web 服务失败,我该如何尝试 3 次?
这是我的代码:
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(Constant.IP);
reqFTP.Credentials = new NetworkCredential(UserName, Password);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();
reader = new StreamReader(responseStream);
如果我的代码无法连接,我想尝试连接到网络服务。只做了3次,我就想放弃了。
我应该如何尝试?
我正在考虑 try catch
并计算失败时间,但我认为会有更好的解决方案。
Here is my code:
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(Constant.IP);
reqFTP.Credentials = new NetworkCredential(UserName, Password);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();
reader = new StreamReader(responseStream);
I would like to try to connect to the web service if my code fails to connect. Only after 3 times, I would like to give up.
How should I try?
I am thinking about try catch
and count the failure time but I think there will be better solutions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将代码封装在循环中,如果没有异常则返回或中断。
Encapsulate your code in loop, and return or break if there is no exception.