码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2014-07-09 11:31:56      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   strong   

在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之后的代码要等到异步方法完成并返回才能执行,但在异步方法执行期间,我们仍然能与应用程序的其他功能进行交互。


Win8.1应用开发之异步编程,布布扣,bubuko.com

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

标签:style   blog   http   color   使用   strong   

原文地址:http://blog.csdn.net/bluecloudmatrix/article/details/37574499

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!