问题的异步Web服务响应
问题描述:
在我的WP7应用程序我打电话和使用这些方法web服务:问题的异步Web服务响应
在我的网页cs文件:
public void Page_Loaded(object sender, RoutedEventArgs e)
{
if (NavigationContext.QueryString["val"] == "One")
{
listAgences=JSON.callWSAgence("http://...");
InitializeComponent();
DataContext = this;
}
}
在我的JSON类,我有这些方法:
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);
}
的问题是,在JSON类的OpenReadCompletedTest方法不正确称为后
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(OpenReadCompletedTestAgence);
所以返回的listAgences是空的。
但后来OpenReadCompletedTest被调用,一切工作都被罚款,但我的视图已被加载。
我能做些什么来进行一种同步调用,或者在webservice响应被解析和我的列表被填充后重新加载我的视图。
答
您看到的行为(问题)是因为网络请求为asynchronously。
如果你想有一个单独的对象调用Web服务器,这将需要处理回调来处理响应或进行适当的更改。
另外:
- 问题中的代码没有显示变量json
被定义为什么。在Page_Loaded
它看起来像一个自定义类,但在OpenReadCompletedTestAgence
和addAgencesToList
它看起来像一个字符串。
- Page_Loaded
中的代码将值设置为listAgences
两次。
有关使台异步调用synchrously Faking synchronous calls in Silverlight WP7
我建议使用无扩展退房以下问题以了解更多信息:http://msdn.microsoft.com/en-us/devlabs/ee794896这将使异步编程更容易... – 2011-01-02 11:30:20