我有一个关于异步方法如何在c上工作的问题。我正在尝试使用convertaddresstocoordinate方法将mylocation变量设置为地理坐标。但是,即使在设置mylocation值之前,也会调用compareDistance方法。在调用compareDistance()之前,如何确保myLocation值不为空?

public GeoCoordinate myLocation = null;

public void returnClosestCurrent(string address)
 {

     convertAddressToCoordinate(address);
     compareDistance(myLocation);

 }

 public void convertAddressToCoordinate(string add)
 {
    WebClient wc = new WebClient();
     wc.DownloadStringCompleted += wc_DownloadStringCompleted;
     wc.DownloadStringAsync(new Uri("http://maps.googleapis.com/maps/api/geocode/json?address=1600+bay+st&sensor=false"));


 }

 void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
 {

    XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);

     var data = from query in xdoc.Descendants("location")
                 select new Location
                 {
                     lat = (string)query.Element("lat"),
                     lng = (string)query.Element("lng")
                 };

     GeoCoordinate destinationGeo = new GeoCoordinate(Convert.ToDouble(data.ElementAt(0).lat), Convert.ToDouble(data.ElementAt(0).lng));

     myLocation = destinationGeo;


 }

最佳答案

可以使用await关键字获取异步任务的值
http://msdn.microsoft.com/en-us/library/vstudio/hh156528.aspx

09-06 21:07