Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WPF

TryRepeat

4.86/5 (11 votes)
9 Sep 2013CPOL 15.1K  
A small tip to retry an action, with an easy to use extension.

Introduction 

This is just a short description of my thoughts of handling exceptions and at the same time offering a retry.

Try Repeat 

I created an extension method just to make it convenient to use. The method extends an Action so that you just have to call (Action).TryRepeat(method) with a method that returns a Boolean to indicate if the action should retry or not. 

C#
/// <summary>
/// Tries the specified action.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="failAction">The fail action.</param>
/// <returns></returns>
public static void TryRepeat(this Action action, Func<Exception, bool> failAction)
{
  bool repeat;
  do
  {
    try
    {
      action();
      return;
    }
    catch (Exception e)
    {
      if (Debugger.IsAttached) Debugger.Break();
      repeat = failAction(e);
    }
  } while (repeat);
}

To use the extension method you can do this:

C#
Action a = () => 
{
   // Put your code here
};
a.TryRepeat(evaluationFunction);

The evaluation function takes the Exception as input and returns a Boolean value to indicate if the action should be repeated. It could look like this:

C#
public static bool HandleException(Exception e)
{
  if (e is SomeException)
  {
    MessageBoxResult result = 
      MessageBox.Show("Connection seems lost, reconnect?", "Error",
                      MessageBoxButton.YesNo);
    return result == MessageBoxResult.Yes;
  }
  return false;
}

Points of Interest 

I'm not thrilled about my idea, mainly because retrying actions might provoke unforeseen errors.

History 

  • 1.0: My initial thoughts.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)