GeoLocator.GetGeopositionAsync With Correct Timeout

To get the current user position in Windows Phone 8 you can use the GeoLocator class that is very comfortable. You get a method containing two overloads.

  • GetGeopositionAsync() – return the current postion (does not have a timeout)
  • GetGeopositionAsync(maximumAge, timeout) – returns a cached position

Sometimes GetGeopositionAsync does not return. So you need to add a timeout procedure by your self. This way is works perfect.

            Geolocator geolocator = new Geolocator();

            // get the async task
            var asyncResult = geolocator.GetGeopositionAsync();
            var task = asyncResult.AsTask();

            // add a race condition - task vs timeout task
            var readyTask = await Task.WhenAny(task, Task.Delay(10000));
            if (readyTask != task) // timeout wins
                throw new TimeoutException();

            // position found within timeout
            var pos = await task;
            return pos;

 

Advertisements

3 thoughts on “GeoLocator.GetGeopositionAsync With Correct Timeout

  1. Eitan says:

    Thanks a lot 🙂

  2. priyanka says:

    thank u so much….god bless u

  3. Sergio says:

    After loosing a couple of hours I found your post. Thank you very much! It works great 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: