我正在尝试做一个简单的应用程序来获取 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;
}