C# 5, with it’s async/await pattern, is extremelly useful for asynchronous development. In Windows 8, the good point is that all the APIs which take more than 50ms must be run asynchronously !
But how do you create your own WinRT component ? This might be simple but there are some tricky points that I wanted to highlight in this blog post.
We know that each WinRT components need to be a sealed class so let’s take a look at the following code:
public sealed class Reader
{
public async static Task<IEnumerable<string>> GetItemsAsync()
{
var feedsTitle = new List<string>();
var client = new SyndicationClient();
var feeds = await client.RetrieveFeedAsync(new Uri(“http://channel9.msdn.com/coding4fun/articles/RSS”));
foreach (var item in feeds.Items)
{
feedsTitle.Add(item.Title.Text);
}
return feedsTitle.AsEnumerable();
}
}
Even if this code seems correct, it’ll fail to compile due to the following error (click on image to enlarge):
The problem here is that each type exposed via your component need to be projected using WinRT. And the compiler is not able to project the Task type.
So we need to create a wrapper that will return (and take in parameters) only types that can be projected. And, for asynchronous operations, the dedicated type is IAsyncOperation<T>, which can be obtained, from a Task object, using the AsAsyncOperation extension’s method:
public sealed class Reader
{
public static IAsyncOperation<IEnumerable<string>> GetItemsAsync()
{
return InternalGetItemsAsync().AsAsyncOperation();
}
internal async static Task<IEnumerable<string>> InternalGetItemsAsync()
{
var feedsTitle = new List<string>();
var client = new SyndicationClient();
var feeds = await client.RetrieveFeedAsync(new Uri(“http://channel9.msdn.com/coding4fun/articles/RSS”));
foreach (var item in feeds.Items)
{
feedsTitle.Add(item.Title.Text);
}
return feedsTitle.AsEnumerable();
}
}
Read more: blog.thomaslebrun.net
QR: