无法在Query Completed Event Args中添加值到List

时间:2014-03-11 20:12:18

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

我有FindRoute循环

  List<double> so = new List<double>;
  private void FindRoute(GeoCoordinate[] wp)
     {
             RouteQuery query = new RouteQuery()
             {
                 TravelMode = TravelMode.Driving,
                 Waypoints =  wp

             };
             query.QueryCompleted += route5Query_QueryCompleted;
             query.QueryAsync();

     }
void route5Query_QueryCompleted(object sender, QueryCompletedEventArgs<Route> e)
    {

        Route myroute = null;
        myroute = e.Result;
        so.Add(myroute.LengthInMeters);

    }

这是按钮点击事件

private void ShortestFindButton_Click(object sender, RoutedEventArgs e)
    { 
          for (int i = 0; i < ZList.Count(); i++)
          {
              FindRoute(ZList[i]);

          }
          MessageBox.Show(so.Count().ToString());

    }

但是当我打电话给.Count()它总是0.我的问题是什么? 谢谢你的帮助

1 个答案:

答案 0 :(得分:0)

您发送查询请求,然后在任何查询有时间响应之前检查结果列表。正如方法QueryAsync所指示的那样,查询是异步。他们不会等到查询完成后再继续。

如果你想要一种简单有效的方法来处理一堆异步操作的结果,那么TPL比其他方法更容易。

首先,我们可以为FindRoute创建一个小型重构,以便在查询完成时返回Task<double>而不是改变列表:

private Task<double> FindRoute(GeoCoordinate[] wp)
{
    RouteQuery query = new RouteQuery()
    {
        TravelMode = TravelMode.Driving,
        Waypoints = wp

    };
    var tcs = new TaskCompletionSource<double>();
    query.QueryCompleted += (s, args) =>
        tcs.TrySetResult(args.Result.LengthInMeters);
    query.QueryAsync();
    return tcs.Task;
}

然后我们可以在这些任务的序列上调用Task.WhenAll来获得所有结果的集合:

private async void ShortestFindButoon_Click(object sender, RoutedEventArgs e)
{
    var so = await Task.WhenAll(
        ZList.Select(coords => FindRoute(coords)));
    MessageBox.Show(so.Count().ToString());
}