In a previous post I was genuinely excited (it’s the developer geek in me) about the use of the asynchronous patterns in Windows Runtime library, however, what is a little less obvious and even more fun is using this pattern within your own code. The example I focused on last post showed us waiting for Task (specifically string), however you can wait for almost anything and everything, in order to do this we take advantage of extension methods, you will probably recognize the pattern.

Waiting for a TimeSpan

public static TaskAwaiter GetAwaiter(this TimeSpan time)
{
    return Task.Delay(time).GetAwaiter();
}

This extension method allows you to treat TimeSpan as you would any asynchronous method as follows:

await TimeSpan.FromMinutes(1);

Waiting for a few seconds

public static TaskAwaiter GetAwaiter(this Int32 seconds)
{
    return TimeSpan.FromSeconds(seconds).GetAwaiter();
}

It seems even more reasonable to wait for specific amount of time, a simple value type like Int32 can now be waitable:

await 600;

You will notice when you hover over both TimeSpan and Int32 intellisense indicates that these types are awaitable.

awaitable





Waiting for your Downloads

So we have really only scratched the surface with the idea of waiting for a specific time frame or a few seconds. As you can imagine you can actually wait on almost any single or even multiple items. In the following example you can asynchronously wait for a series of downloads, this could just as easily be a list of processes, services, or events.

public static TaskAwaiter GetAwaiter(this IEnumerable<task> tasks)
{
    return Task.WhenAll(tasks).GetAwaiter();
}

The following allows you to wait for all the downloads to complete before continuing using the WhenAll (completes when all the supplied tasks have completed).

List<string> urls = new List<string>();
urls.Add("http://www.PoppaString.com");
urls.Add("http:///www.PoppaString.com/apps");
urls.Add("http:///www.PoppaString.com/design");

HttpClient client = new HttpClient();
await from url in urls select client.GetStringAsync("url");


Comment Section

Comments are closed.