Windows Phone 8 Asynchronous Pending

I just started learning WP programming, so this might be a bit of a dumb question ...

Im a development application that retrieves data from one web service in several different ways. So I decided to put this whole set of web services in one class:

class WebApiWorker { public async Task<List<GeocodeResponse>> GetGeocodeAsync(String address) { String url = "http://api.com&search=" + HttpUtility.UrlEncode(address) + "&format=json"; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.Method = "GET"; HttpWebResponse response = (HttpWebResponse) await httpWebRequest.GetResponseAsync(); Stream responseStream = response.GetResponseStream(); string data; using (var reader = new System.IO.StreamReader(responseStream)) { data = reader.ReadToEnd(); } responseStream.Close(); var geocodeResponse = JsonConvert.DeserializeObject<List<GeocodeResponse>>(data); return geocodeResponse; } } 

But as I should call it from my โ€œmain applicationโ€, I try something like this:

 WebApiWorker webApi = new WebApiWorker(); var geoResponse = await webApi.GetGeocodeAsync("address"); 

So what's wrong with this, I get a compiler error: The wait statement can only be used in an asynchronous method. Consider labeling this method with the async modifier and change its return type to Task.

All suggestions are welcome.

+4
source share
2 answers

Make sure your method in the "main application" code also has the "async" modifier:

 public async Task GetAddress() { WebApiWorker webApi = new WebApiWorker(); var geoResponse = await webApi.GetGeocodeAsync("address"); } 
+4
source

The answer to this question depends a little on what you want from the answer. Are you going to use the result right away? If so, then you are not using asynchronous functionality at all, and you can simply make the other version of your function synchronous. If your calling function is intended to continue later, do as Chris (and your compiler) said; make an asynchronous call function.

It is true that ultimately the root subscriber should not be asynchronous; Typically, this will be the void method, which returns nothing. (In fact, the indicated void will return before your asynchronous functions)

0
source

Source: https://habr.com/ru/post/1486045/


All Articles