C# TryAgain

Date: 2021-09-28

For the methods that at random do not work

public static T RunSync<T>(Func<Task<T>> fn) => Task.Run(fn).GetAwaiter().GetResult();
public static T TryAgain<T>(Func<Task<T>> action, int count = 3)
{
Exception lastException = null;
while(count > 0)
{
try
{
var result = RunSync(async () => await action());
return result;
}
catch (Exception ex)
{
lastException = ex;
}
Thread.Sleep(200); // This can be adjusted at will
count -= 1;
}
throw lastException;
}
// Example usage:
var prodOrder = TryAgain(async () =>
{
// next line works like a traffic light
prodOrder = await api.Query<ProductionOrder>(x => x.id == id);
if (prodOrder == null)
throw new Exception("Production order not found!");
return prodOrder;
});
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
53950cookie-checkC# TryAgain
0 of 2000 max characters.