如果我的代码无法在c#中连接web服务,我该如何尝试3次?

本文关键字:服务 3次 何尝试 web 连接 代码 我的 如果 | 更新日期: 2023-09-27 18:16:16

下面是我的代码:

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);

如果我的代码连接失败,我想尝试连接到web服务。只有在三次之后,我才想放弃。

我该如何尝试?

我正在考虑try catch并计算失败时间,但我认为会有更好的解决方案。

如果我的代码无法在c#中连接web服务,我该如何尝试3次?

int faultCounter = 0;
bool faulted;
do {
  faulted = false;
  try {
    // perform service operation
  } catch {
    faultCounter++;
    faulted = true;
  }
} while (faulted && faultCounter < 3);

将代码封装在循环中,如果没有异常,则返回或中断。