c# - 等待异步操作完成

标签 c# windows windows-phone-7 windows-phone-8

我有一个关于异步方法如何在 C# 上工作的问题。我正在尝试使用 convertAddressToCoordinate 方法将 myLocation 变量设置为 GeoCoordinate。但是,甚至在设置 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

关于c# - 等待异步操作完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15672568/

相关文章:

c# - 防止通过键盘 XAML 突出显示/选择?

c# - 我将如何创建 Windows Phone Live Camera Feed?

windows - 为什么 Docker 无法在 Windows 10 Home 中检测到 WSL 2 发行版?

silverlight - WP7 ProgressBar高度和颜色问题

windows-phone-7 - Windows 手机操作系统 7.0 与操作系统 7.1

c# - 安全异常 : Request for the permission of type 'System.Net.Mail.SmtpPermission'

c# - Web API 中的身份验证

javascript - 使用 SignalR、WebApi 和服务

.net - 如果存在 Microsoft SQL Server 实例,则绕过 SQLExpress 的安装

windows-phone-7 - Windows Phone 上的 Azure ACS token 续订