Reputation: 1362
I'm trying to get the geo coords for several addresses in a list like that:
private void setRestaurant()
{
foreach (Restaurant restaurant in allRestaurant)
{
GeoCoordinate help;
GeocodeQuery query = new GeocodeQuery()
{
GeoCoordinate = new GeoCoordinate(0, 0),
SearchTerm = restaurant.address
};
query.QueryCompleted += (s, e) =>
{
foreach (var item in e.Result)
{
help = item.GeoCoordinate;
restaurants.Add(restaurant);
}
};
query.QueryAsync();
}
}
Because of something it cant get the geocord for any of them ( sometimes it finds one). The addresses are correct, i am sure of that , i tried them out one by one without iteration, so the bug is somewhere within this code. Any idea?
Thanks!
Upvotes: 1
Views: 111
Reputation: 3683
This is why:
foreach (Restaurant restaurant in allRestaurant)
{
GeoCoordinate help;
GeocodeQuery query = new GeocodeQuery()
{
GeoCoordinate = new GeoCoordinate(),
SearchTerm = restaurant.address
};
TaskCompletionSource<Restaurant> task = new TaskCompletionSource<Restaurant>();
query.QueryCompleted += (s, ev) =>
{
foreach (var item in ev.Result)
{
help = item.GeoCoordinate;
task.TrySetResult(restaurant);
}
task.TrySetResult(null);
};
query.QueryAsync();
var rest = (await task.Task);
if (rest != null)
restaurants.Add(rest);
}
It seems you cannot run multiple queries so you must wait before checking another address.
Upvotes: 2