Tuesday, January 11, 2011

Retrying Code Execution

I have a bit of code I'm working on at work that makes use of an HTTP endpoint to notify a legacy system of certain events. Because the network is not reliable, we have to handle the case when the network may be down. In this situation, it means to try again a few times, after which the processing request goes into an error queue, where it can be handled manually. So, I started out with something like this:

This calls the HTTP endpoint up to five times. If one of those times succeeds, it returns the result and stops trying. If it gets to the sixth time, it gives up.

Now, in my project, I have several of these types of calls to make. Much of the above code, namely the exception handling and flow control stuff, is common to all of them. So, using some functional .NET and an extension method, we can do this:

This will attempt to execute and return the value of func up to times times, and give up after that. With this extension method, we can now put our endpoint-calling code in a Func<int> and tell it to try to call the endpoint up to five times, like this: Now, is this the best way to do this? Maybe; maybe not. It's just something I've been toying around with in my attempts to eliminate duplication of the aforementioned ugly flow control code. I'll have to walk around in these shoes for a while and see whether I like them.