简体   繁体   中英

How i can set delay method to my upload function C#

I am using upload function in my desktop application. i want if upload function become unsuccessful then this method retry to upload it. Currently when upload is unsuccessful then it be me error of unhandled exception .i need solution of this

 **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#

Just write your own retry handler. Or use Polly (recommended, as it's a mature and very successful library).

However, this is an example of how you might build your own.

Given

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);
   }
}

Usage

await RetryOnExceptionAsync(3, 1000, Uploaded);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM