Win8.1应用开发之异步编程

本文介绍在Win8应用商店开发中如何使用异步方法RetrieveFeedAsync来下载信息,保持应用良好响应,并通过示例代码展示具体实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在win8应用商店开发时,我们会遇到许多异步方法,它们存在的目的就是为了确保你的应用在执行需要大量时间的任务时仍能保持良好的响应,也就是说调用异步API是为了响应用户的操作。设想一下我们点击一个Button,会从网上下载一些信息,如果没有异步,我们就不得不等它下载完才能继续进行操作。为了能在下载时保持响应,windows提供了一个用于下载源的异步方法SyndicationClient.RetrieveFeedAsync

// Put the keyword, async on the declaration of the event handler.
private async void Button_Click_1(object sender, RoutedEventArgs e)
{

    Windows.Web.Syndication.SyndicationClient client = new SyndicationClient();

    // Force the SyndicationClient to download the information.
    client.BypassCacheOnRetrieve = true;

    Uri feedUri
        = new Uri("http://windowsteamblog.com/windows/b/windowsexperience/atom.aspx");

    try
    {
        // Call SyndicationClient RetrieveFeedAsync to download the list of blog posts.
        SyndicationFeed feed = await client.RetrieveFeedAsync(feedUri);

        // The rest of this method executes after await RetrieveFeedAsync completes.
        rssOutput.Text = feed.Title.Text + Environment.NewLine;

        foreach (SyndicationItem item in feed.Items)
        {
            rssOutput.Text += item.Title.Text + ", " +
                             item.PublishedDate.ToString() + Environment.NewLine;
        }
    }
    catch (Exception ex)
    {
        // Log Error.
        rssOutput.Text =
            "I'm sorry, but I couldn't load the page," +
            " possibly due to network problems." +
            "Here's the error message I received: "
            + ex.ToString();
    }
}

异步方法的名字以Async结尾,在调用异步方法时需要使用运算符await,告知编译器这是个异步方法,要注意要在使用了await运算符的方法(如上为Button_Click_1)的声明中加上关键字async。

其实上面程序的执行流为:当执行到await作用的异步方法时,await之后的代码要等到异步方法完成并返回才能执行,但在异步方法执行期间,我们仍然能与应用程序的其他功能进行交互。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值