Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeating a function in C# until it no longer throws an exception

Tags:

c#

exception

I've got a class that calls a SOAP interface, and gets an array of data back. However, if this request times out, it throws an exception. This is good. However, I want my program to attempt to make this call again. If it times out, I'd like it to keep making this call until it succeeds. How can I accomplish this?

For example:

try
{
   salesOrdersArray = MagServ.salesOrderList(sessID, filter);
}
catch
{
   ?? What Goes Here to FORCE the above line of code to rerun until it succeeds.
}
like image 268
psyklopz Avatar asked Oct 27 '11 18:10

psyklopz


People also ask

Is there a repeat function in C?

Loops are used to repeat a block of code.

How do you write Repeat until in C?

The basic syntax for a repeat / until loop looks like this: repeat DoSomething(); DoSomethingElse(); until x ≥ 10; where a conditional expression is specified after the closing until keyword, and a list of statements can be provided between the repeat and until keywords.

What is looping in C?

The looping can be defined as repeating the same process multiple times until a specific condition satisfies. It is known as iteration also. There are three types of loops used in the C language. In this part of the tutorial, we are going to learn all the aspects of C loops..

What is a repeat loop?

A repeat loop is used any time you want to execute one or more statements repeatedly some number of times. The statements to be repeated are preceded by one of the repeat statements described below, and must always be followed by an end repeat statement to mark the end of the loop. Repeat loops may be nested.


1 Answers

You just need to loop forever:

while (true)
{
    try
    {
        salesOrdersArray = MagServ.salesOrderList(sessID, filter);
        break; // Exit the loop. Could return from the method, depending
               // on what it does...
    }
    catch
    {
        // Log, I suspect...
    }
}

Note that you should almost certainly not actually loop forever. You should almost certainly have a maximum number of attempts, and probably only catch specific exceptions. Catching all exceptions forever could be appalling... imagine if salesOrderList (unconventional method name, btw) throws ArgumentNullException because you've got a bug and filter is null... do you really want to tie up 100% of your CPU forever?

like image 158
Jon Skeet Avatar answered Sep 17 '22 21:09

Jon Skeet