简体   繁体   中英

Windows Phone 8 async await usage

I have just started learning WP programming so this might be little silly question...

Im developing app which fetch data from one web services few different method. So I decided to put all this web service fetching code to 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 how I should call this from my "main app" code, im trying something like this:

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

So whats wrong with this, i get the compiler error: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

All suggestions are welcome.

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

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

The answer to this one slightly depends on what you want from the response. Are you going to use the result right away? If so, then you're not really using asynchronous functionality at all, and can just make another version of your function that is synchronous. If your calling function is meant to continue later, then do as Chris (and your compiler) said; make the calling function async.

It's true that eventually, a root caller will need to be NOT async; generally, that one will be a void method that doesn't return anything. (In fact, said void will return before your asynchronous functions do)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM