Over a million developers have joined DZone.

Adding synchronous methods to WebRequest on Windows Phone 7

· Mobile Zone

In general, I really like developing for Windows Phone 7. The tools like Visual Studio and Blend are of excellent quality and both Silverlight and XNA are very good frameworks. I only have one big annoyance and that’s the fact WebRequest does not support synchronous method calls. I am completely aware of the fact that you should not do heavy operations on the UI thread and I perform all my REST calls on a background thread, but I don’t like the fact that Microsoft forces me to make these calls asynchronously. As a developer, I would prefer to make this choice myself.

I have created 2 simple extension methods to add synchronous behavior to WebRequest.

public static class WebRequestExtensions
{
	public static WebResponse GetResponse(this WebRequest request)
	{
		AutoResetEvent autoResetEvent = new AutoResetEvent(false);

		IAsyncResult asyncResult = request.BeginGetResponse(r => autoResetEvent.Set(), null);

		// Wait until the call is finished
		autoResetEvent.WaitOne();

		return request.EndGetResponse(asyncResult);
	}

	public static Stream GetRequestStream(this WebRequest request)
	{
		AutoResetEvent autoResetEvent = new AutoResetEvent(false);

		IAsyncResult asyncResult = request.BeginGetRequestStream(r => autoResetEvent.Set(), null);

		// Wait until the call is finished
		autoResetEvent.WaitOne();

		return request.EndGetRequestStream(asyncResult);
	}
}

Please note: using an AutoResetEvent comes with a performance penalty, so this code is less efficient than a real synchronous method implementation.

Plase note 2: I know that you normally can also retrieve a WaitHandle from an IAsyncResult object instead of creating an AutoResetEvent manually, but this is not possible on WP7.

Topics:

Published at DZone with permission of Pieter De Rycke, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}