HttpWebRequest.GetResponse and GetRequestStream in Windows Phone 7

Windows Phone 7, at least on the Silverlight side of things, is very heavily biased toward asynchronous API calls.  While that’s all well and good, it makes porting existing code assets to the Phone a bit more challenging. 


One place I recently ran into was in making synchronous calls to HttpWebRequest.GetResponse and GetRequestStream.  These methods don’t exist in the Phone 7 SDK – instead you should use BeginGetResponse and BeginGetRequestStream.  Well my code was written to use the synchronous versions and is shared with CF and FFx applications, so rewriting the calling code isn’t terribly appealing. Instead I simply added the following extensions to the project:


 

namespace System.Net
{
public static class HttpWebRequestExtensions
{
#if WINDOWS_PHONE
private const int DefaultRequestTimeout = 5000;

public static HttpWebResponse GetResponse(this HttpWebRequest request)
{
var dataReady = new AutoResetEvent(false);
HttpWebResponse response = null;
var callback = new AsyncCallback(delegate(IAsyncResult asynchronousResult)
{
response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
dataReady.Set();
});

request.BeginGetResponse(callback, request);

if (dataReady.WaitOne(DefaultRequestTimeout))
{
return response;
}

return null;
}

public static Stream GetRequestStream(this HttpWebRequest request)
{
var dataReady = new AutoResetEvent(false);
Stream stream = null;
var callback = new AsyncCallback(delegate(IAsyncResult asynchronousResult)
{
stream = (Stream)request.EndGetRequestStream(asynchronousResult);
dataReady.Set();
});

request.BeginGetRequestStream(callback, request);
if (!dataReady.WaitOne(DefaultRequestTimeout))
{
return null;
}

return stream;
}
#endif
}
}

3 Comments

  1. I’ve encountered an odd issue the extension methods.

    I generally prefer using background threads for network IO and was going to write similar methods, but found yours and am trying them out. Problem for me seems to be that the call back delegate isn’t being called until the calling thread exits. So essentially the timeout occurs on the WaitOne(), and at a later time the call back returns successfully. I’ve set the timeout to be different periods and that isn’t the issue, and I’ve verified all is getting called off the UIThread, and thoughts?

Leave a Reply