Skip to content

Instantly share code, notes, and snippets.

@hodzanassredin
Created October 24, 2011 19:42
Show Gist options
  • Select an option

  • Save hodzanassredin/1309941 to your computer and use it in GitHub Desktop.

Select an option

Save hodzanassredin/1309941 to your computer and use it in GitHub Desktop.
try retry in c# in functional
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FaultTolerance
{
class Program
{
static void Main(string[] args)
{
var start = 2;
Console.WriteLine(Retry<int>(5,
() => Do(start, 1),
() => Do(start, 2),
() => Do(start, 3),
() => Do2(start)).Value);
Console.ReadKey();
}
public static Either<int> Do(int a, int version)
{
Console.WriteLine("Do with version " + version);
return Either<int>.Error;
}
public static Either<int> Do2(int a)
{
Console.WriteLine("Do2");
return new Either<int>(a);
}
public static Either<T> Retry<T>(int times, params Func<Either<T>>[] fns)
{
Console.WriteLine("attempts to remain " + times);
var fn = fns[times % fns.Length];
if (times > 1)
{
var res = fn();
if (res.HasError) return Retry(times - 1, fns);
else return res;
}
return fn();
}
}
public class Either<T>
{
public static readonly Either<T> Error = new Either<T>();
public bool HasError { get; private set; }
public T Value { get; private set; }
public Either()
{
HasError = true;
}
public Either(T value)
{
Value = value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment