I'm working on some code to do an HttpRequest via Task.Factory.FromAsync (in a WP7 app).
The task's Result property is always null, but I know the request itself is correct, because if I paste it into my browser or Fiddler, it works. This is my code:
string _url = string.Format("http://requestapi.net/{0}/{1}/{2}",
"objects","partitionKey","pkey1");
var request = (HttpWebRequest)WebRequest.Create(_url);
request.Method = "GET";
Task<WebResponse> task1 = Task<WebResponse>.Factory.FromAsync(
(callback, o) => ((HttpWebRequest)o).BeginGetResponse(callback, o)
, result => ((HttpWebRequest)result.AsyncState).EndGetResponse(result)
, request);
task1.Start();
WebResponse webResponse = task1.Result;
string responseString;
using (var response = (HttpWebResponse)webResponse)
{
using (Stream streamResponse = response.GetResponseStream())
{
StreamReader reader = new StreamReader(streamResponse);
responseString = reader.ReadToEnd();
reader.Close();
}
}
UPDATE: on WP7, the TPL is only available via Nuget. I downloaded it here: http://nuget.org/packages/System.Threading.Tasks
UPDATE: This works. Mike was right - the task just wasn't finished executing. I'm not sure why task1.Result didn't wait automatically (it's supposed to implicitly call task1.wait()), but this is the working code. Please let me know if you see other problems with this! This code starts where the task1.Start() used to be - which is now removed.
//task1.Start();
string responseString;
task1.ContinueWith((antecedent) =>
{
WebResponse webResponse = task1.Result;
using (var response = (HttpWebResponse)webResponse)
{
using (Stream streamResponse = response.GetResponseStream())
{
StreamReader reader = new StreamReader(streamResponse);
responseString = reader.ReadToEnd();
reader.Close();
}
}
});