的Windows Phone 8异步等待用法 [英] Windows Phone 8 async await usage

查看:164
本文介绍了的Windows Phone 8异步等待用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习编程的WP所以这可能是有点愚蠢的问题...

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

林开发应用程序,它从一个Web服务的一些不同的方法获取数据。所以我决定把所有的Web服务获取code到一个类:

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;

    }
}

不过,我应该如何从我的主要的应用程序code调用这个,我尝试这样的:

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'.

所有建议都欢迎。

推荐答案

请确保你的方法在你的主应用程序code也有异步修改

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");
}

这篇关于的Windows Phone 8异步等待用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆