Change this
var response = task.Result;
to this
var response = await task;
await
returns the result of the task or unwraps the AggregateException
, if any.
Also, .Result
blocks the current thread until the result is available, and that's probably not what you want, otherwise you'd just be using the blocking GetResponse
, instead of the async BeginGetResponse
and EndGetResponse
.
Also, you don't even need those two methods. There's a better one - GetResponseAsync
Use this:
var response = await req.GetResponseAsync();
Instead of this:
Task<WebResponse> task = Task.Factory.FromAsync(
req.BeginGetResponse,
asyncResult => req.EndGetResponse(asyncResult),
(object)null);
var response = task.Result;