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
}
}