HOW TO: Use Await In Windows 8 Style Metro Coding

With the release of the new Visual Studio 11, and Microsoft 8, comes a new display and coding style targeting Metro. Metro is a display system that was modeled after a Swiss system of subway trains that allowed users to interact and purchase their tickets quickly and efficiently. A new very exciting keyword is being presented with the demos that are up called Await. What this keyword allows us to do is execute an asynchronous function or subroutine and move on with our code. This option is available very easily and does not require any timers or threading to handle any complex processes.
Here is a great example of how to use Await while reading a feed from a blog.

VB.NET

Private Async Function GetFeedAsync(FeedUriString As String) As Task
' Imports Windows.Web.Syndication
Dim Client As New SyndicationClient
Dim FeedUri As New Uri(FeedUriString)
Try
Dim Feed As SyndicationFeed = Await Client.RetrieveFeedAsync(FeedUri)
Dim FeedData As New FeedData
FeedData.Title = Feed.Title.Text

For Each Item As SyndicationItem In Feed.Items
Dim FeedItem As New FeedItem
FeedItem.Title = Item.Title.Text
FeedItem.PubDate = Item.PublishedDate.DateTime
FeedItem.Author = Item.Authors(0).Name.ToString()

If Feed.SourceFormat = SyndicationFormat.Atom10 Then
FeedItem.Content = Item.Content.Text
ElseIf Feed.SourceFormat = SyndicationFormat.Rss20 Then
FeedItem.Content = Item.Summary.Text
End If

FeedData.Items.Add(FeedItem)
Next

Me.DataContext = FeedData
ItemListView.SelectedIndex = 0
Catch Ex As Exception
' Log Error.
TitleText.Text = Ex.Message
End TryEnd Function

C#

private async Task GetFeedAsync(string feedUriString){
// using Windows.Web.Syndication;
SyndicationClient client = new SyndicationClient();
Uri feedUri = new Uri(feedUriString);

try {
SyndicationFeed feed = await client.RetrieveFeedAsync(feedUri);
FeedData feedData = new FeedData();
feedData.Title = feed.Title.Text;

foreach (SyndicationItem item in feed.Items)
{
FeedItem feedItem = new FeedItem();
feedItem.Title = item.Title.Text;
feedItem.PubDate = item.PublishedDate.DateTime;
feedItem.Author = item.Authors[0].Name.ToString();
if (feed.SourceFormat == SyndicationFormat.Atom10)
{
feedItem.Content = item.Content.Text;
}
else if (feed.SourceFormat == SyndicationFormat.Rss20)
{
feedItem.Content = item.Summary.Text;
}
feedData.Items.Add(feedItem);
}
this.DataContext = feedData;
ItemListView.SelectedIndex = 0;
}
catch (Exception ex)
{
// Log Error.
TitleText.Text = ex.Message;
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>