HttpClient
would be a better choice. If you can't use it for any reason, wrap BeginGetResponse
/BeginGetResponse
with Task.Factory.FromAsync
, as an extension method:
static public Task<WebResponse> GetResponseAsTaskAsync(this WebRequest @this)
{
return Task.Factory.FromAsync(
(asyncCallback, state) =>
@this.BeginGetResponse(asyncCallback, state),
(asyncResult) =>
@this.EndGetResponse(asyncResult), null);
}
Then you do a blocking call like this:
var response = request.GetResponseAsTaskAsync().Result;
If you do a series of request, one after another, you should keep this logic asynchronous and let the client of your PCL library to decide whether to block or not. Something like this:
static public async Task<WebResponse> GetManyResponsesAsync(string[] urls)
{
WebResponse lastResponse = null;
foreach (url in urls)
{
var request = WebRequest.Create(url);
var response = await request.GetResponseAsTaskAsync();
// .. process response
lastResponse = response;
}
return lastResponse;
}
The caller would have a choice to await
on the result of GetManyResponsesAsync
, or block with GetManyResponsesAsync().Result
.