zoukankan      html  css  js  c++  java
  • Win8.1应用开发之异步编程

    在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)的声明中加上keywordasync。

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


  • 相关阅读:
    c语言中重要函数
    python 类属性、对象属性
    windows下PIP安装模块编码错误解决
    python爬取百思不得姐视频
    ubuntu下刷新dns
    pycharm设置安装python第三方插件
    python将str转换成字典
    pyqt加载图片
    Python端口扫描器
    自己构造用于异步请求的JSON数据
  • 原文地址:https://www.cnblogs.com/yxwkf/p/5170707.html
Copyright © 2011-2022 走看看