views:

708

answers:

2

We will need to call out to a 3rd party to retrieve a value using REST, however if we do not receive a response within 10ms, I want to use a default value and continue processing.

I'm leaning towards using an asynchronous WebRequest do to this, but I was wondering if there was a trick to doing it using a synchronous request.

Any advice?

+2  A: 

If you are doing a request and waiting on it to return I'd say stay synchronous - there's no reason to do an async request if you're not going to do anything or stay responsive while waiting.

For a sync call:

WebRequest request = WebRequest.Create("http://something.somewhere/url");
WebResponse response = null;
request.Timeout = 10000; // 10 second timeout
try
{
    response = request.GetResponse();
}
catch(WebException e)
{
  if( e.Status == WebExceptionStatus.Timeout)
  {
    //something
  }
}

If doing async:

You will have to call Abort() on the request object - you'll need to check the timeout yourself, there's no built-in way to enforce a hard timeout.

Philip Rieck
Wouldn't going asynchronous allow the CPU to settle down while it waited for the callback?Maybe not, but thats what I did with a service I wrote. It calls a website every 30 sec, but it does it asynchronously. If the 30 seconds comes around before the last request finishes is goes back to sleep.
Jason Stevenson
With .NET web services at least, synchronous calls are really asynchronous under the hood anyway.
MusiGenesis
A: 

You could encapsulate your call to the 3rd party in a WebService. You could then call this WebService synchronously from your application - the web service reference has a simple timeout property that you can set to 10 seconds or whatever.

Your call to get the 3rd party data from your WebService will throw a WebException after the timeout period has elapsed. You catch it and use a default value instead.

EDIT: Philip's response above is better. RIF.

MusiGenesis