How to implement re-try n times in case of exception in C#?
static T TryNTimes<T>(Func<T> func, int times)
{
while (times>0)
{
try
{
return func();
}
catch(Exception e)
{
if (--times <= 0)
throw;
}
}
}
I wrote this code not too long ago to do something similar to what you want. It can be modified to fit your needs. It's a generic wait method. Pass in a function and if the expected result is not returned, wait then retry and exit after X number of tries.
/// <summary>
/// Wait for the result of func to return the expeceted result
/// </summary>
/// <param name="func">Function to execute each cycle</param>
/// <param name="result">Desired result returned by func</param>
/// <param name="waitInterval">How long to wait (ms) per cycle </param>
/// <param name="cycles">How many times to execute func before failing</param>
/// <returns>True if desired result was attained. False if specified time runs out before desired result is returned by func</returns>
protected static bool WaitForEvent(Func<bool> func, bool result, int waitInterval, int cycles)
{
int waitCount = 0;
while (func() != result)
{
if (waitCount++ < cycles)
{
Thread.Sleep(waitInterval);
}
else
{
return false;
}
}
return true;
}
while(retries < maxTries)
try
{
//retryable code here
break;
}
catch(Exception ex)
{
if(++retries == maxTries)
throw;
continue;
}
Certainly nothing fancy but it'll get the job done. The main pattern, which would be common to pretty much any implementation, is some looping construct containing and somewhat controlled by a try-catch; that can either be a recursive call or some iterative loop such as the while loop above. Make sure you exit the loop properly after a successful attempt, and keep track of retries; failure to do either will cause an infinite loop.