Dans mon application WP7 j'appelle et consommer un webservice avec ces méthodes:problème avec réponse webservice asynchrone
Dans le fichier de ma page:
public void Page_Loaded(object sender, RoutedEventArgs e)
{
if (NavigationContext.QueryString["val"] == "One")
{
listAgences=JSON.callWSAgence("http://...");
InitializeComponent();
DataContext = this;
}
}
Dans ma classe JSON j'ai ces méthodes :
public List<Agence> callWSAgence(string url)
{
WebClient webClient = new WebClient();
Uri uri = new Uri(url);
webClient.OpenReadAsync(uri);
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(OpenReadCompletedTestAgence);
return listAgences;
}
public void OpenReadCompletedTestAgence(object sender, OpenReadCompletedEventArgs e)
{
StreamReader reader = new System.IO.StreamReader(e.Result);
jsonResultString = reader.ReadToEnd().ToString();
addAgencesToList();
reader.Close();
}
public void addAgencesToList()
{
jsonResultString = json.Substring(5, json.Length - 6);
listAgences = JsonConvert.DeserializeObject<List<Agence>>(json);
}
le problème est que la méthode OpenReadCompletedTest dans la classe JSON n'est pas appelé juste après
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(OpenReadCompletedTestAgence);
Ainsi, la listeAgences renvoyée est vide.
Mais plus tard, OpenReadCompletedTest est appelé et tout fonctionne correctement, mais ma vue a déjà été chargée. Que puis-je faire pour avoir une sorte d'appel synchrone ou pour recharger ma vue après l'analyse de la réponse webservice et ma liste remplie.
Je recommande d'utiliser des extensions réactives: http://msdn.microsoft.com/en-us/devlabs/ee794896 Il fera la programmation async plus facile ... –