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?
How about:
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/awaitwith*Asyncmethods. They simply return aTask<T>object that you can work with and use methods likeWait,ContinueWith, etc… Much easier than dealing with theBegin/End(APM pattern)…FWIW the
*Asyncpattern 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…).