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

时间:2023-03-09 06:06:50
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之后的代码要等到异步方法完毕并返回才干运行,但在异步方法运行期间。我们仍然能与应用程序的其它功能进行交互。