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?
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.
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.
You have a few options:
- Block waiting for
CurrentLocation
to be resolved. Not the greatest solution, UI might freeze etc - Implement a simple callback mechanism
- Check for the status and leave (i.e. call it from wait loop of some sort)
SOLVED: http://msdn.microsoft.com/en-us/library/ff431782(v=VS.92).aspx
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.
精彩评论