.net 如果失败,是否重试SFTP?

6qfn3psc  于 2023-01-22  发布在  .NET
关注(0)|答案(1)|浏览(129)

我正在使用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];
    }
}
4c8rllxm

4c8rllxm1#

推荐的重试方法是瞬时故障处理库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 .. */
    }
});

相关问题