如何调用异步方法?

时间:2012-06-10 11:13:06

标签: c# windows-8 microsoft-metro async-await

我正在尝试创建一个简单的应用程序来获取Windows 8中的当前位置,但我无法找到await关键字的正确语法。

错误说: 错误1“await”运算符只能在异步方法中使用。考虑使用'async'修饰符标记此方法并将其返回类型更改为'Task'。

代码如下:

public MainPage()
        {
            this.InitializeComponent();

            TextBlock txt = new TextBlock();           
            var location = await InitializeLocationServices();
            txt.Text = location;

            Grid.SetRow(txt, 0);
            Grid.SetColumn(txt, 1);
            //InitializeLocationServices();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private async Task<string> InitializeLocationServices()
        {
            //Initialize geolocator object
            Geolocator geoLocator = new Geolocator();
            if (null != geoLocator)
                try
                {
                    //Try resolve the current location
                    var position = await geoLocator.GetGeopositionAsync();
                    if (null != position)
                    {
                        string city = position.CivicAddress.City;
                        string country = position.CivicAddress.Country;
                        string state = position.CivicAddress.State;
                        string zip = position.CivicAddress.PostalCode;
                        string msg = "I am located in " + country;
                        if (city.Length > 0)
                            msg += ", city of " + city;
                        if (state.Length > 0)
                            msg += ", " + state;
                        if (zip.Length > 0)
                            msg += " near zip code " + zip;
                        return msg;
                    }
                    return string.Empty;
                }
                catch (Exception)
                {
                    //Nothing to do - no GPS signal or some timeout occured.n .
                    return string.Empty;
                }
            return string.Empty;
        }

2 个答案:

答案 0 :(得分:3)

所以它不起作用,因为你在构造函数中调用它。

我不熟悉Win8,但是从OnNavigatedTo的描述中,“///属性通常用于配置页面。”

它可能是初始化的良好候选者。让我们试着把它移到那里:

protected async override void OnNavigatedTo(NavigationEventArgs e)
{

   TextBlock txt = new TextBlock();           
   var location = await InitializeLocationServices();
   txt.Text = location;

   Grid.SetRow(txt, 0);
   Grid.SetColumn(txt, 1);
}

答案 1 :(得分:1)

请记住,您的函数会返回Task<string>,那么您如何两次返回string

return string.Empty;

旁注。我无法理解这项检查

Geolocator geoLocator = new Geolocator();
        if (null != geoLocator)