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

后端 未结 11 2084
一生所求
一生所求 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:40

    You must place the try/catch block inside a loop construct. If you wish not to consume 100% of your processor place a Thread.Sleep in the catch block, so everytime an exception occurs, it will wait some time, freeing the processor to do other things.

    // iterate 100 times... not forever!
    for (int i = 0; i < 100; i++)
    {
        try {
            // do your work here;
    
            break; // break the loop if everything is fine
        } catch {
            Thread.Sleep(1000);
        }
    }
    

    You could also specify exception type, so that only the timeout exception is handled, and other kinds of exceptions pass-through.

    // iterate 100 times... not forever!
    for (int i = 0; i < 100; i++)
    {
        try {
            // do your work here;
    
            break; // break the loop if everything is fine
        } catch (TimeOutException) {
            Thread.Sleep(1000);
        }
    }
    

    Note that, TimeOutException should be replaced by the real name of the exception... I don't know if that is the real name.

    Also adjust the sleep time, given in millisecs and the amount of repeats, in the case I presented, 100 repeats of 1000ms yields a maximum wait of 1 minute and 40 seconds, plus the operation time itself.

提交回复
热议问题