I am developing a WPF 4.0 application in which we get the data from a remote web service. The web service exposes around 120+ methods to its clients. If a web service call from my WPF application fails, I need to retry it n times which is configurable via App.Config. How to implement this? Are there any design patterns that address this problem?
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;
}
static T TryNTimes<T>(Func<T> func, int times)
{
while (times>0)
{
try
{
return func();
}
catch(Exception e)
{
if (--times <= 0)
throw;
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With