等待异步操作完成

时间:2013-03-28 01:17:00

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

我对异步方法如何在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;


 }

3 个答案:

答案 0 :(得分:2)

您可以使用await关键字获取异步任务的值

http://msdn.microsoft.com/en-us/library/vstudio/hh156528.aspx

答案 1 :(得分:1)

在您的代码中,我认为只应在compareDistance(myLocation);方法的末尾调用wc_DownloadStringCompleted

在改变之后,一切都应该正常。

答案 2 :(得分:1)

您需要await wc.DownloadStringAsync

public async Task returnClosestCurrent(string address)
{
    await convertAddressToCoordinate(address)
              .ContinueWith(t => compareDistance(myLocation));
}

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

async / await的模式是代码倾向于将所有内容都变为async / await

可以重构使用WebClient.DownloadStringTaskAsync

public async Task ReturnClosestCurrent(string address)
{
    await convertAddressToCoordinate(address)
            .ContinueWith(t => compareDistance(t.Result));
}

public async Task<GeoCoordinate> ConvertAddressToCoordinate(string add)
{
    WebClient wc = new WebClient();
    wc.DownloadStringCompleted += wc_DownloadStringCompleted;
    var content = await wc.DownloadStringTaskAsync(new Uri("http://maps.googleapis.com/maps/api/geocode/json?address=1600+bay+st&sensor=false"));

    return ParseContent(content);
}

private GeoCoordinate ParseContent(string content)
{
    XDocument xdoc = XDocument.Parse(content, 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));

    return destinationGeo;
}