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

后端 未结 11 2172
一生所求
一生所求 2021-01-18 00:31

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 m

11条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-18 00:39

    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?

提交回复
热议问题