c# - 我如何为我的上传函数 C# 设置延迟方法
问题描述
我在我的桌面应用程序中使用上传功能。我想如果上传功能不成功,那么这个方法重试上传。目前,当上传不成功时,这是我未处理异常的错误。我需要解决这个问题
**This is function**
async Task Uploaded()
{
using (var dbx = new DropboxClient(token))
{
bmp = new Bitmap(picboxcapture.Image);
string folder = "/folder/"+Login.recuser+"";
string filename = DateTime.Now.ToString() + " " + " " + MyTodo_Project.rectsk + ".JPG";
string URL = picboxcapture.Image.ToString();
ImageConverter converter = new ImageConverter();
MemoryStream(File.ReadAllBytes(@"C:\Users\home\Downloads\FazalNEwTEst.JPG"));
byte[] bytes = (byte[])converter.ConvertTo(picboxcapture.Image, typeof(byte[]));
var mem = new MemoryStream(bytes);
var updated = dbx.Files.UploadAsync(folder + "/" + filename,
WriteMode.Overwrite.Instance, body: mem);
updated.Wait();
var tx = dbx.Sharing.CreateSharedLinkWithSettingsAsync(folder + "/" + filename);
tx.Wait();
URL = tx.Result.Url;
}
}
**The function call**
private async void save_Load(object sender, EventArgs e)
{
await Uploaded();
}
I want that when upload unsuccessful then it will retry to upload it in page load event . how can
i do this in C#
解决方案
只需编写您自己的重试处理程序。或者使用Polly(推荐,因为它是一个成熟且非常成功的库)。
但是,这是您如何构建自己的示例。
给定
public class RetriesExceededException : Exception
{
public RetriesExceededException() { }
public RetriesExceededException(string message) : base(message) { }
public RetriesExceededException(string message, Exception innerException) : base(message, innerException) { }
}
public static async Task RetryOnExceptionAsync(int retryCount, int msDelay, Func<Task> func)
{
for (var i = 0; i < retryCount; i++)
{
try
{
await func.Invoke();
return;
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
if (i == retryCount - 1)
throw new RetriesExceededException($"{retryCount} retries failed", ex);
}
await Task.Delay(msDelay)
.ConfigureAwait(false);
}
}
用法
await RetryOnExceptionAsync(3, 1000, Uploaded);
推荐阅读
- ios - 如何编写返回响应的alamofire请求函数?
- python - tf.keras 手动设备放置
- c# - 如何在图表列表中计算值的总和?[ 解决了 ]
- tomcat - 每次更改某些内容时,我都必须在 Tomcat 的 webapps 中手动重新加载 war 文件。我怎样才能自动完成?
- extbase - 如何在 TYPO3 9.5 中返工 addAdditionalHeaderData
- javascript - 在代码中完成时 HTTP 请求不起作用
- if-statement - 如何在jmeter中实现if else
- php - 如何在 symfony 学说中编写子查询
- redis-cluster - 如何使用远程服务器运行 redis 客户端?
- java - 带有用于交叉点的自定义顶点的 Java 图形可视化包