Cyan
Cyan

Reputation: 1118

Threading - make sure the thread finishes

SOLVED: http://msdn.microsoft.com/en-us/library/ff431782(v=VS.92).aspx

I have the following class that will give me the current location in WP7:

public class Position
{
    private GeoCoordinateWatcher watcher = null;
    public GeoCoordinate CurrentLocation { get; set; }

    public Position()
    {
        ObtainCurrentLocation();
    }

    private void ObtainCurrentLocation()
    {
        watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
        watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
        watcher.Start();
    }

    void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
    {
        //stop & clean up, we don't need it anymore
        watcher.Stop();
        watcher.Dispose();
        watcher = null;

        CurrentLocation = e.Position.Location;
    }

}

I want to use it to get the location. So what I do is to instantiate it. How can I make sure that, when I call the CurrentLocation property, the location whould have been acquired?

Upvotes: 0

Views: 325

Answers (5)

Peter Wone
Peter Wone

Reputation: 18775

I am amazed that people don't know this stuff, the web abounds with tutorials and texts and this is one of the commoner topics.

Here's a good primer that's not too big: Silverlight for Windows Phone - learn & practise

And here, available from Microsoft Press at no charge, is Charles Petzold's Programming Windows Phone 7

Surprisingly, while the first book is a skinny thing in mangled English by some obscure Indonesian guy, it's easy to follow and it contains important stuff that's not in Petzold - such as how to use an InputScope, which is how you get that groovy list of suggested words while you type into a TextBox.

Upvotes: -1

Andr&#233;as Saudemont
Andr&#233;as Saudemont

Reputation: 1353

You can make your Position class implement INotifyPropertyChanged and raise PropertyChanged when the value of the CurrentLocation property has changed.

Code that depends on CurrentLocation will then listen for Position.PropertyChanged and act appropriately when the event is raised.

Upvotes: 2

Tralamazza
Tralamazza

Reputation: 316

You have a few options:

  1. Block waiting for CurrentLocation to be resolved. Not the greatest solution, UI might freeze etc
  2. Implement a simple callback mechanism
  3. Check for the status and leave (i.e. call it from wait loop of some sort)

Upvotes: 1

Den
Den

Reputation: 16826

First of all, I would highly recommend avoiding automatically getting the location on class instantiation. This complicates a lot of things. Second, I would recommend returning a GeoCoordinate through a method. Say you have a public GeoCoordinate GetCoordinate() that will return you the result - use it that way. This will make it a bit easier to get the data in a synchronous manner.

Upvotes: 4

Related Questions