我想做一個簡單的應用程序,獲取當前位置在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;
}
問題是你想要在構造函數中調用它,這是不可能的,我不認爲,更不用說一個可怕的想法開始。這有SO問題有「CAn構造函數是異步」的答案http://stackoverflow.com/questions/8145479/can-constructors-be-async –
你可以請提供代碼我該如何解決這個問題?我不介意從構造函數中移動它。 –
dunno,不熟悉win8應用程序頁面生命週期,也許嘗試調用它OnNavigatedTo並將其標記爲async –