How to call an asynchronous method in Windows 8.

Posted on

In my application, I wanted to get the current location, but because it might take some seconds, I wanted to do it asynchronously.

Normally, you would put this code on the constructor of the class, but if you are using the await keyword, then the method using must be async, and you cant put async in constructors.


So the way to do it, is to rewrite the onnavigatedto method


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

 private async Task<string> InitializeLocationServices()
            //Initialize geolocator object
            Geolocator geoLocator = new Geolocator();
            if (null != geoLocator)
                    //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;


One thought on “How to call an asynchronous method in Windows 8.

    xyzzer said:
    June 11, 2012 at 5:11 pm

    You can’t make the constructor async, but you can call an async method from the constructor – just can’t await one, so you can have another method that you would call from your constructor that would then await InitializeLocationServices(). That’s if you want to start an async operation as soon as possible.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s