简体   繁体   中英

c# or vb Generic function to retry code block n number of times

I am trying to create a generic function to which I can specify the method to be called & number of times it should try getting result before it fails.

Something like:

//3 stands for maximum number of times GetCustomerbyId should be called if it fails on first attempt.
var result = RetryCall(GetCustomerbyId(id),3);

Secondly the return type should be adjusted automatically based on function it is calling.

For example I should be able to get result from both of following function, one returns string & other Customer entity.

public static string GetCustomerFullNamebyId(int id){
    return dataContext.Customers.Where(c => c.Id.Equals(id)).SingleOrDefault().FullName;
}

public static Customer GetCustomerbyId(int id){
   return dataContext.Customers.Find(id);
}

Is this possible?

You can do the following:

public T Retry<T>(Func<T> getter, int count)
{
  for (int i = 0; i < (count - 1); i++)
  {
    try
    {
      return getter();
    }
    catch (Exception e)
    {
      // Log e
    }
  }

  return getter();
}

const int retryCount = 3;

Customer customer = Retry(() => GetCustomerByID(id), retryCount);
string customerFullName = Retry(() => GetCustomerFullNamebyId(id), retryCount);

question is what to do in case of exception during the first n attempts? I guess you could just log the exception but be aware the caller won't see it.

You could also do a loop function and set a variable to see the if the number of tries attempted match the number of tries you actually want it to do.

    private static void DoSomeTask(int RetryCount)
    {
        int Count = 0;
        while (Count != RetryCount)
        {
            DoCustomerLookUp(); // or whatever you want to do
            Count++;
        }
    }

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