Windows phone 7 Windows Phone 7-等待Webclient完成
我正在开发一个应用程序,遇到了一个异步调用问题。。。这就是我要做的 该应用程序使用JSON API,并且在运行时,使用必要的值(即单个新闻文章)填充全景项目中的列表框。当用户选择一个列表框项目时,SelectionChanged事件被触发——它从所选项目中提取articleID,并将其传递给更新方法,以下载该项目的JSON响应,使用JSON.NET对其进行反序列化,并将用户带到WebBrowser控件,该控件根据收到的响应呈现html页面 问题是,我必须等待响应后才能启动NavigationService,但我不确定如何正确执行。这样,代码运行“太快”,我无法及时得到响应来呈现页面 事件代码:Windows phone 7 Windows Phone 7-等待Webclient完成,windows-phone-7,asynchronous,Windows Phone 7,Asynchronous,我正在开发一个应用程序,遇到了一个异步调用问题。。。这就是我要做的 该应用程序使用JSON API,并且在运行时,使用必要的值(即单个新闻文章)填充全景项目中的列表框。当用户选择一个列表框项目时,SelectionChanged事件被触发——它从所选项目中提取articleID,并将其传递给更新方法,以下载该项目的JSON响应,使用JSON.NET对其进行反序列化,并将用户带到WebBrowser控件,该控件根据收到的响应呈现html页面 问题是,我必须等待响应后才能启动NavigationSe
private void lstNews_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lstNews.SelectedIndex == -1)
{
return;
}
ShowArticle _article = new ShowArticle();
ListBox lb = (ListBox)sender;
GetArticles item = (GetArticles)lb.SelectedItem;
string passId = ApiRepository.ApiEndpoints.GetArticleResponseByID(item.Id);
App.Current.JsonModel.JsonUri = passId;
App.Current.JsonModel.Update();
lstNews.SelectedIndex = -1;
NavigationService.Navigate(new Uri("/View.xaml?id=" + item.Id, UriKind.Relative));
}
视图中的OnNavigatedTo方法:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
long sentString = long.Parse(NavigationContext.QueryString["id"]);
string articleUri = ApiRepository.ApiEndpoints.GetArticleResponseByID(Convert.ToInt32(sentString));
//this throws an error, runs "too fast"
_article = App.Current.JsonModel.ArticleItems[0];
}
更新方法:
public void Update()
{
ShowArticle article = new ShowArticle();
try
{
webClient.DownloadStringCompleted += (p, q) =>
{
if (q.Error == null)
{
var deserialized = JsonConvert.DeserializeObject<ShowArticle>(q.Result);
_articleItems.Clear();
_articleItems.Add(deserialized);
}
};
}
catch (Exception ex)
{
//ignore this
}
webClient.DownloadStringAsync(new Uri(jsonUri));
}
public void Update()
{
ShowArticle=新ShowArticle();
尝试
{
webClient.DownloadStringCompleted+=(p,q)=>
{
如果(q.Error==null)
{
var deserialized=JsonConvert.DeserializeObject(q.Result);
_articleItems.Clear();
_articleItems.Add(反序列化);
}
};
}
捕获(例外情况除外)
{
//忽略这一点
}
下载StringAsync(新Uri(jsonUri));
}
异步回调模式:
public void Update(Action callback, Action<Exception> error)
{
webClient.DownloadStringCompleted += (p, q) =>
{
if (q.Error == null)
{
// do something
callback();
}
else
{
error(q.Error);
}
};
webClient.DownloadStringAsync(new Uri(jsonUri));
}
非常感谢。这正是我需要它做的。在这种情况下,如果它回答了你的问题,接受答案。
App.Current.JsonModel.Update(() =>
{
// executes after async completion
NavigationService.Navigate(new Uri("/View.xaml?id=" + item.Id, UriKind.Relative));
},
(error) =>
{
// error handling
});
// executes just after async call above