Oli
Oli

Reputation: 3136

Setting Timeout On HttpWebRequest.BeginGetResponse

I have a class library that I'm porting to a Windows 8 Store Class Library. One of the methods uses the now not supported synchronous HttpWebRequest. I need to keep the method synchronous as the Async work has been done in the applications not the library and changing it would take a great deal of effort. I've changed it to a Synchronous task with IAsyncresult but I'm not sure how to set the request timeout using this code. Can someone help? Also can anyone see any other issues I may encounter with this code?

//Create Web Request
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
IAsyncResult asyncResult = request.BeginGetResponse(null, null);

if (asyncResult.AsyncWaitHandle.WaitOne(5 * 1000))
{
    //Get Response
    using (HttpWebResponse response = request.EndGetResponse(asyncResult) as HttpWebResponse)
    {
        if (request.HaveResponse && response != null)
        {
            using (Stream reader = response.GetResponseStream())
            {
                result = XDocument.Load(reader);
            }
        }
    }
}
else
{
    request.Abort();
}

UPDATE: I've added a waithandle to the request and if it times out I abort the httpwebrequest. Does this take care of any threads started by HttpWebRequest?

Upvotes: 0

Views: 2825

Answers (1)

Peter Ritchie
Peter Ritchie

Reputation: 35869

How about:

if(false == request.GetResponseAsync().Wait(DateTime.Now.AddMinutes(2.0)))
{
    Trace.WriteLine("timeout");
    return;
}
//...

Now keep in mind, this is simply the timeout to wait on the asynchronous operation. To specifically deal with a timeout on the response/requeststream operation, see HttpWebRequest.Timeout.

You don't have to use async/await with *Async methods. They simply return a Task<T> object that you can work with and use methods like Wait, ContinueWith, etc... Much easier than dealing with the Begin/End (APM pattern)...

FWIW the *Async pattern is called the Task Asynchronous Pattern (TAP). It seems to be the recommended pattern now, replacing the Asynchronous Programming Model (APM, Begin/End) and Event-based Asynchronous Pattern (EPM, Completed, CancelAsync, etc...).

Upvotes: 1

Related Questions