2

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();
                    }
                }
            });
4

1 に答える 1

1

You're basically creating a task, but not waiting for it to complete before checking the result. From the comments, it seems the WP7 runtime and framework work a bit differently from the full CLR, which would block when you tried to get the result. The Silverlight runtime is very anti-blocking-things.

You'll want to use the await keyword (which is available on newer runtimes or using the Async Targeting Pack if you have VS2012) or the ContinueWith method to start your task asynchronously.

于 2012-11-30T19:54:46.747 に答える