问题描述:

I have multithreaded operation which performs a series of tasks. The problem i'm facing is a webservice that might return an Timeout when under heavy stress.

When under heavy stress (Timeout), I want the function to retry

Try

{

// Do some actions here

}

catch(WebException ex)

{

if (// Timeout)

{ //Retry }

else

{ // return error }

}

catch(Exception ex)

{ //return error }

From MSDN An Webexception can occur in the following situations:

  • Abort was previously called.
  • The time-out period for the request expired.
  • An error occurred while processing the request.

Question:

In my exceptionhandling, how can seperate these 3 causes and single out the TimeoutExceptions without using the message?

Note: I know i could just increase the timeout to resolve the issue. But that doesn't statify my curiosity.

Thank you for your time

网友答案:

You can inspect Status property comparing to one of the web request status codes:

try {

}
catch(WebException ex) {
    if (ex.Status == WebExceptionStatus.Timeout) {
        // Retry logic
    }
    else {
        // return error
    }
}

See also this post for an example of retry logic. Please note that Timeout isn't the only reason that should trigger a retry (IMO also ConnectionFailure and ConnectionClosed, at least).

网友答案:

You can take a look at the Status property of the Exception, which will contain the correct reason for the exception.

Since you are using some time-related behaviors, if you use some tests in your code I would recommend taking a look at the Reactive extensions; it lets you configure event chains that can allow you to easily tests desired behaviors. Look at this question for an example where I wanted some events to repeat are a higher frequency in case of an error, which may interest you.

相关阅读:
Top