我正在使用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];
}
}
答案 0 :(得分:1)
重试的推荐方法是瞬态故障处理库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 .. */
}
});