The Task: Async and Await in a Windows Runtime World

In my last blog post, I covered how to wrap your arms around the Task class and its relationship to the new async and await keywords. I mentioned that the post was focused on the .NET Framework only because the Windows Runtime handles these operations differently. In this post, I’ll cover what those differences are.

Task is a Task is a Task

First, in the Windows Runtime, a Task is a Task … is a Task. You can write your code to return a Task or Task<T> in your Windows 8 Metro applications. If you are going to expose a Windows Runtime (WinRT) component, however, one of the rules is that you must always return a WinRT type. For asynchronous operations, there are four types allowed:

No Result Returns Results
No Progress or Cancellation IAsyncAction IAsyncOperation<TResult>
Supports Progress and/or Cancellation IAsyncActionWithProgress<TProgress> IAsyncOperationWithProgress<TResult, TProgress>

The type you return depends on whether or not you return a result, and whether or not you support checking progress and/or cancellation.

Task is a IAsyncAction or IAsyncOperation<T>

If you don’t support progress or cancellation, returning the necessary type is easy: simply use a Task and return it using one of the extension methods to convert it to the corresponding WinRT type. For example, the following useless piece of code iterates through all of the availabl

e integers and returns nothing:

public static IAsyncAction IterateAsync()
{
   return Task.Run(() =>
   {
      for(int x = Int.MinValue; x < Int.MaxValue; x++) ;
   }).AsAsyncAction();
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/white-space: pre;/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

For a more practical example, consider the multiplication method I used in the last blog post. To convert that to a result, I simply do:

public IAsyncOperation<int> Multiply(int a, int b)
{
   return Task.Run(() => a * b)
      .AsAsyncOperation();
}

That’s fairly simple and straightforward. What about supporting progress and/or cancellation?

Forget Tasks: The 411 on AsyncInfo

The AsyncInfo class is there to assist you with performing asynchronous actions or operations that support cancellation and reporting progress.

public static IAsyncOperationWithProgress<int, double> Multiply(int a, int b)
{
   return AsyncInfo.Run<IList<long>, double>((token, progress) =>
      Task.Run<int>(() =>
      {
         progress.Report(0);
         var result = a*b;
         token.ThrowIfCancellationRequested();
         progress.Report(100.0);
         return result;
      }, token));
}

Obviously the operation is a bit contrived as the multiplication operation doesn’t take as long, but hopefully this simple example illustrates the point of what is possible. The IAsyncActionWithProgress will work the same way, it simply doesn’t return a result.

There you have it … the scoop on the new async and await keywords and how they behave both with and without the Windows Runtime. Now that you have the basics, head over to Stephen Toub’s blog post and read the far more in depth Diving Deep with WinRT and await.
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Jeremy Likness

View Comments

  • Hey,
    thanks for that Information - helped me a lot today!
    (Difference betweent Action and Operation).
    Alex

  • you are actually a good webmaster. The site loading velocity is incredible. It seems that you are doing any distinctive trick. Also, The contents are masterwork. you've done a fantastic process on this subject!

  • Can you explain, why if I use await operator in threads with SynchronizationContext not null ( from "UI thread" WinForms for example) - than application will "freeze" ? Seems like that "callback thread" from await can't access to the threads with SynchronizationContext not null ...

  • Can you explain, why if I use await operator in threads with SynchronizationContext not null ( from "UI thread" WinForms for example) - than application will "freeze" ? Seems like that "callback thread" from await can't access to the threads with SynchronizationContext not null ...

Recent Posts

8-Step AWS to Microsoft Azure Migration Strategy

Microsoft Azure and Amazon Web Services (AWS) are two of the most popular cloud platforms.…

2 days ago

How to Navigate Azure Governance

 Cloud management is difficult to do manually, especially if you work with multiple cloud…

1 week ago

Why Azure’s Scalability is Your Key to Business Growth & Efficiency

Azure’s scalable infrastructure is often cited as one of the primary reasons why it's the…

3 weeks ago

Unlocking the Power of AI in your Software Development Life Cycle (SDLC)

https://www.youtube.com/watch?v=wDzCN0d8SeA Watch our "Unlocking the Power of AI in your Software Development Life Cycle (SDLC)"…

1 month ago

The Role of FinOps in Accelerating Business Innovation

FinOps is a strategic approach to managing cloud costs. It combines financial management best practices…

1 month ago

Azure Kubernetes Security Best Practices

Using Kubernetes with Azure combines the power of Kubernetes container orchestration and the cloud capabilities…

2 months ago