0

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

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

代码如下:

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;
        }
4

2 回答 2

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);
}
于 2012-06-10T11:52:31.923 回答
1

记住你的函数返回Task<string>了,那么你怎么会返回string两次呢?

return string.Empty;

旁注。我无法理解这张支票

Geolocator geoLocator = new Geolocator();
        if (null != geoLocator)
于 2012-06-10T11:21:37.190 回答