0

I may be misunderstanding the flow of control, because by all accounts this seems like it should work. This is a Windows phone 8 app. I am attempting to make a web request, and accordingly display the data returned. I am trying to get the data (here, called 'Key') in the following method:

public Task<String> getSingleStockQuote(String URI)
    {
        return Task.Run(() =>
            {
                String key = null;
                HttpWebRequest request = HttpWebRequest.Create(URI) as HttpWebRequest;
                HttpWebResponse response;
                try
                {
                    request.BeginGetResponse((asyncres) =>
                        {
                            HttpWebRequest responseRequest = (HttpWebRequest)asyncres.AsyncState;
                            response = (HttpWebResponse)responseRequest.EndGetResponse(asyncres);
                            key = returnStringFromStream(response.GetResponseStream());
                            System.Diagnostics.Debug.WriteLine(key);
                        }, request);

                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine("WebAccessRT getSingleStockQuote threw exception");
                    key = String.Empty;
                }
                return key;
            });
    }

...And I am calling this method like so:

WebAccessRT rt = new WebAccessRT();
      await rt.getSingleStockQuote(stockTagURI);
System.Diagnostics.Debug.WriteLine("Past load data");

The WriteLine() in BeginGetResponse is for testing purposes; it prints after "Past Load Data". I want BeginGetResponse to run and complete operation (thus setting the Key), before the task returns. The data prints out right in the console, but not in the desired order - so Key is set and has a value, but its the very last part that gets run. Can someone point me in the right direction and/or see what's causing the problem above? Thinking this through, is the await operator SIMPLY waiting for the Task to return, which is returning after spinning off its async call?

Carlos
  • 105
  • 1
  • 9
  • Use `GetResponseAsync` with `async/await`. If you can't use `async/await`, check this: http://stackoverflow.com/q/21345673/1768303 – noseratio May 08 '14 at 22:50
  • you can also use callback mechanism and do "Past load data" in callback event handler. – vITs May 09 '14 at 11:56

1 Answers1

1

BeginGetResponse starts an asynchronous process (hence the callback) so you cannot guarantee the order it is completed. Remember that the code within BeginGetResponse is actually a separate method (see closures) that is executed separately from getSingleStockQuote. You would need to use await GetResponseAsync or (imo, even better - you could greatly simplify your code) use HttpClient.

earthling
  • 5,084
  • 9
  • 46
  • 90