Carlos
Carlos

Reputation: 105

WP8 Async/Await begingetresponse not waiting, gets run last

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?

Upvotes: 0

Views: 963

Answers (1)

earthling
earthling

Reputation: 5264

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.

Upvotes: 1

Related Questions