Windows Phone 7的 - 等待Web客户端完成 [英] Windows Phone 7 - wait for Webclient to complete

查看:109
本文介绍了Windows Phone 7的 - 等待Web客户端完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个应用程序,并遇到了与异步调用的一个问题...这就是我要做的。

该应用程序消耗JSON API,并在运行时,填写必要的值全景项中的列表框(即单次新闻文章)。当用户选择一个列表框项,SelectionChanged事件被触发 - 它拿起从所选项目的条款ArticleID,并把它传递到更新方法下载的文章的JSON响应,JSON.NET反序列化,并采取用户可以从收到的响应呈现一个HTML页面WebBrowser控件。

这样做的问题是,我必须等待响应之前,我启动的NavigationService,但我不知道该怎么做正确的。这样,code运行太快了,我没有得到我的响应时间来渲染页面。

本次活动code:

 私人无效lstNews_SelectionChanged(对象发件人,SelectionChangedEventArgs E)
    {
        如果(lstNews.SelectedIndex == -1)
        {
            返回;
        }        ShowArticle _Article =新ShowArticle();
        列表框磅=(列表框)发送;
        GetArticles项目=(GetArticles)lb.SelectedItem;
        字符串passId = ApiRepository.ApiEndpoints.GetArticleResponseByID(item.Id);
        App.Current.JsonModel.JsonUri = passId;
        App.Current.JsonModel.Update();        lstNews.SelectedIndex = -1;        NavigationService.Navigate(新的URI(?/ View.xaml ID =+ item.Id,UriKind.Relative));
    }

的OnNavigatedTo方法查看:

 保护覆盖无效的OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs E)
    {
        base.OnNavigatedTo(E);        长sentString = long.Parse(NavigationContext.QueryString [ID]);        字符串articleUri = ApiRepository.ApiEndpoints.GetArticleResponseByID(Convert.ToInt32(sentString));        //这会引发错误,运行速度过快
        _Article = App.Current.JsonModel.ArticleItems [0];
    }

update方法:

 公共无效更新()
    {
        ShowArticle文章=新ShowArticle();        尝试
        {
            webClient.DownloadStringCompleted + =(P,Q)=>
            {
                如果(q.Error == NULL)
                {
                    无功反序列化= JsonConvert.DeserializeObject< ShowArticle>(q.Result);
                    _articleItems.Clear();
                    _articleItems.Add(反序列化);
                }
            };
        }        赶上(异常前)
        {
            //忽略这个
        }        webClient.DownloadStringAsync(新的URI(jsonUri));
    }


解决方案

异步回调格局:

 公共无效更新(动作回调,动作<异常和GT;错误)
{
    webClient.DownloadStringCompleted + =(P,Q)=>
    {
        如果(q.Error == NULL)
        {
            // 做一点事
            回电话();
        }
        其他
        {
            错误(q.Error);
        }
    };
    webClient.DownloadStringAsync(新的URI(jsonUri));
}

电话:

  App.Current.JsonModel.Update(()=>
{
    //异步完成后执行
    NavigationService.Navigate(新的URI(?/ View.xaml ID =+ item.Id,UriKind.Relative));
},
(错误)=>
{
    //错误处理
});
//略高于异步调用后执行

I'm developing an app and have run into a problem with asynchronous calls... Here's what i'm trying to do.

The app consumes a JSON API, and, when run, fills the ListBox within a panorama item with the necessary values (i.e. a single news article). When a user selects a ListBox item, the SelectionChanged event is fired - it picks up the articleID from the selected item, and passes it to an Update method to download the JSON response for the article, deserialize it with JSON.NET, and taking the user to the WebBrowser control which renders a html page from the response received.

The problem with this is that I have to wait for the response before I start the NavigationService, but I'm not sure how to do that properly. This way, the code runs "too fast" and I don't get my response in time to render the page.

The event code:

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 method in the View:

    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];
    }

The update method:

    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));
    }

解决方案

async callback pattern:

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));
}

call:

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

这篇关于Windows Phone 7的 - 等待Web客户端完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆