我有一個關於異步方法如何在c#上工作的問題。我正在嘗試獲取convertAddressToCoordinate方法來將myLocation變量設置爲GeoCoordinate。但是,即使在myLocation值設置之前,也會調用compareDistance方法。如何在調用compareDistance()之前確保myLocation值不爲null?等待異步操作完成
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關鍵字在代碼中呢? DownloadStringAsync()沒有返回類型。 – 2013-03-28 01:28:28
我認爲更好的方法是在下載字符串事件中移動'compareDistance'方法 – 2013-03-28 01:31:36