Which is the best way to add a retry/rollback mechanism for sync/async tasks in C#?

后端 未结 5 953
后悔当初
后悔当初 2021-02-04 01:15

Imagine of a WebForms application where there is a main method named CreateAll(). I can describe the process of the method tasks step by step as follows:

1) Stores to da

5条回答
  •  温柔的废话
    2021-02-04 01:49

    Some code that may help you to achieve your goal.

    public static class Retry
    {
       public static void Do(
           Action action,
           TimeSpan retryInterval,
           int retryCount = 3)
       {
           Do(() => 
           {
               action();
               return null;
           }, retryInterval, retryCount);
       }
    
       public static T Do(
           Func action, 
           TimeSpan retryInterval,
           int retryCount = 3)
       {
           var exceptions = new List();
    
           for (int retry = 0; retry < retryCount; retry++)
           {
              try
              { 
                  if (retry > 0)
                      Thread.Sleep(retryInterval);
                  return action();
              }
              catch (Exception ex)
              { 
                  exceptions.Add(ex);
              }
           }
    
           throw new AggregateException(exceptions);
       }
    }
    
    
    

    Call and retry as below:

    int result = Retry.Do(SomeFunctionWhichReturnsInt, TimeSpan.FromSeconds(1), 4);
    

    Ref: http://gist.github.com/KennyBu/ac56371b1666a949daf8

    提交回复
    热议问题