Windows Phone 8 - Asynchronous Webrequest
The Windows Phone 8 SDK provides the class WebRequest as well as the possibility to use async / await. But how ever there are no (extension) methods GetRequestStreamAsync and GetResponseAsync. The class WebRequest supports the asynchronous access via the old fashioned interface IAsyncResult of those functions. So you can build your own await able extension methods like this.
public static class HttpExtensions {
public static Task<Stream> GetRequestStreamAsync(this HttpWebRequest request) {
var taskComplete = new TaskCompletionSource<Stream>();
request.BeginGetRequestStream(asyncResponse => {
try {
var responseRequest = (HttpWebRequest)asyncResponse.AsyncState;
var someResponse = (Stream)responseRequest.EndGetRequestStream(asyncResponse);
taskComplete.TrySetResult(someResponse);
} catch (WebException webExc) {
var failedResponse = (HttpWebResponse)webExc.Response;
taskComplete.TrySetResult(null);
}
}, request);
return taskComplete.Task;
}
public static Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request) {
var taskComplete = new TaskCompletionSource<HttpWebResponse>();
request.BeginGetResponse(asyncResponse => {
try {
var responseRequest = (HttpWebRequest)asyncResponse.AsyncState;
var someResponse = (HttpWebResponse)responseRequest.EndGetResponse(asyncResponse);
taskComplete.TrySetResult(someResponse);
} catch (WebException webExc) {
var failedResponse = (HttpWebResponse)webExc.Response;
taskComplete.TrySetResult(failedResponse);
}
}, request);
return taskComplete.Task;
}
}
}