Threading - make sure the thread finishes

半世苍凉 提交于 2019-12-25 03:09:12

问题


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?


回答1:


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.




回答2:


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.




回答3:


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)



回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/5956960/threading-make-sure-the-thread-finishes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!