首页 > 解决方案 > 我如何为我的上传函数 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#

标签: c#winforms

解决方案


只需编写您自己的重试处理程序。或者使用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);

推荐阅读