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

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

    I follow this pattern in order to solve this problem:

        public void Send(String data, Int32 attemptNumber)
        {
            try
            {
                yourCodeHere(data);
            }
            catch (WebException ex)
            {
                if (attemptNumber > 0)
                    Send(data, --attemptNumber);
                else
                    throw new AttemptNumberExceededException("Attempt number exceeded!", ex);
            }
            catch (Exception ex)
            {
                //Log pourpose code goes here!
                throw;
            }
        }
    

    Trying forever seems not to be a good idea as you may end up having an infinite process. If you think you need many attempts to achieve your goal just set huge number here.

    I personally think its wise to wait some milliseconds, or seconds after eac attempt Thread.Sleep(1000); before callig Send(data); --- you could for example, use the attempNumber variable to increse or decrease this waiting time if you think its wise for your scenario.

提交回复
热议问题