I am relatively new to C#, maybe you could help me with this.
I got a couple of methods callServiceXY(param1, param2, ...) that call a certain service. For many reasons these service calls can go wrong (and I don’t really care for the reason in the end). So basically I need to always wrap them with something like this – to have them execute again if something goes wrong:
var i = 3;
while(i>0)
try{
call...()
} catch{
i--;
}
i=0;
}
I’d rather write this code only once. Could I somehow have a method like tryXtimes(int x, callService()) that allows me to execute an undefined or anonymous method? (I have Javascript in mind where this is possible…)?
Yes this is possible. C# 3.5 added support for
ActionandFunc<T>types. An Action won’t return any value, a Func will always return a value.You have several different versions that also accept a number of parameters. The following Console Applications describes how you could do this:
As you can see, there are two overloads for
ExecuteWithRetry. One returning void, one returning a type. You can callExecuteWithRetryby passing anActionor aFunc.–> Edit: Awesome! Just a little extra code to complete the example:
With anonymous function/method:
And with more parameters (action, int)
Method header:
Method call: