如果失败重试 SFTP?

Retry SFTP if it fails?

我正在使用 SSH.Net 上传,但如果过程失败,我想重试 SFTP 文件。我有这段代码,但我认为这不是处理重试的最佳方式。处理此问题的最佳方法是什么?

        var exceptions = new List<Exception>();
        int retryCount = 3;

        for (int retry = 0; retry < retryCount; retry++)
        {
            try
            {
                var filePath = Path.Combine(path, fileName);

                var client = new SftpClient("ftp.site.com", 22, "userName", "password");

                client.Connect();

                if (client.IsConnected)
                {
                    var fileStream = new FileStream(filePath, FileMode.Open);
                    if (fileStream != null)
                    {
                        client.UploadFile(fileStream, "/fileshare/" + fileName, null);

                        client.Disconnect();
                        client.Dispose();
                    }

                }
            }
            catch (Exception ex)
            {
                exceptions.Add(ex);
                System.Threading.Thread.Sleep(10000);
            }

            if (exceptions.Count == 3)
            {
                throw exceptions[0];
            }
        }

推荐的重试方法是瞬态故障处理库 Polly

var retryPolicy = Policy
  .Handle<Exception>()
  .WaitAndRetry(3, retryAttempt => 
    TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)) 
  );

retryPolicy.Execute(() => {
    using (var client = new SftpClient("ftp.site.com", 22, "userName", "password")) 
    {
        /* file uploading .. */
    }
});