Retry a service call ONLY ONCE in the event service fails logic help
So I have a function that calls a web service which will return an INT indicitating success or various types of failures that may have occurred. After I recieve the result from the service, I then run through a switch statement and procceed accordingly based on what was encountered during the service execution.
private void Example()
{
int Result = ExecuteWebService();
swi开发者_开发技巧tch(Result)
{
case 0:
//no errors
NoErrorsLogic();
break;
case 1:
// manual retry
ManualRetryLogic();
break;
case 2:
// validation error
ValidationErrorLogic();
break;
default:
// Run time error occurred
LogicOptionD();
// At this point I want to to call the service again ONCE just to see if it will succeed
break;
}
}
Generally, I'd just add a call to the function so it calls the sevice and runs through the results all over again, but I don't want it to continuously run until the service succeeds. In the default option I simply want to force it to 'retry' calling the service ONCE - and THEN process the results accordingly.
Any ideas?
You can alwaus do:
private void Example(bool retry = true)
{
....
default:
if(retry)
{
Example(false);
}
break;
}
Just add a parameter and have the function call itself if it fails. You pass in the false value for the parameter that tells the function that if it fails again, don't do anything.
In C# 4.0 Example(bool retry = true)
you can set a default value, so you don't have to worry about your existing code not having true value already set. In 3.5 or below just create an overloaded method on with the parameter and one without. The one without just calls the one with so:
Example()
{
Example(true);
}
While I agree with Kevin approach, here goes another one:
bool success = false;
bool retry = true;
while (!success)
{
success = true;
int Result = ExecuteWebService();
switch(Result)
{
case 0:
//no errors
NoErrorsLogic();
break;
case 1:
// manual retry
ManualRetryLogic();
break;
case 2:
// validation error
ValidationErrorLogic();
break;
default:
// Run time error occurred
LogicOptionD();
success = !retry;
retry = false;
break;
}
}
This will ensure that if there is another logic in Example, it will be called once anyway, and you will not need to place the service call and response processing code into a separate method (I would recommend to do that, though).
精彩评论