More on Async, Win8, and C#

I had to fly out early on Friday, so the only session I attended on Friday was Mads Torgersen and Alex Turner’s talk on the async features in C# 5.0. I’ll start with the punchline:

In C# and async, you’ll never write another callback.

In a nutshell, that’s what these features add to the language: Transformations so that you can write code that looks and reads like today’s synchronous code, and the compiler will transform that into the necessary constructs for async behavior. The compiler will create the state machine, and write the callback code for you.

The second key point is that all the languages (C++/C#/VB.NET/F#/Javascript) all support this construct. It’s also baked into the WinRT libraries. You can await WinRT async operations, just like you can await C# async methods.

There is, however, one very important distinction:

C# / .NET tasks are created “hot”, meaning they start immediately. WinRT async methods are created “cold”, meaning they don’t start until you await them.

The .NET languages are leveraging Task<T> and extension methods which take or return Task<T> to make the operation of WinRT async methods behave as similar as possible to C# async methods. For example, you can use the Start() and StartAsTask() extension methods to start a WinRT async operation. StartAsTask() also massages the WinRT awaitable to a C# Task<T> so that it supports cancellation.

Task<T> is also used to provide some other useful async constructs. Task.Run() enables you to write a compute intensive task for a background thread, and leverage the await pattern. The library handles the thread marshaling so that the continuation executes on the foreground thread when the background thread finishes its work.

Task<T> also contains the Task.Delay() method that you can use to easily check for timeouts expiring in long running operations.

Admittedly, this is a short post. Watch their talk, and try it out yourself.

You’ll never write another callback.

Created: 9/19/2011 5:27:05 PM

Current Projects

I create content for .NET Core. My work appears in the .NET Core documentation site. I'm primarily responsible for the section that will help you learn C#.

All of these projects are Open Source (using the Creative Commons license for content, and the MIT license for code). If you would like to contribute, visit our GitHub Repository. Or, if you have questions, comments, or ideas for improvement, please create an issue for us.

I'm also the president of Humanitarian Toolbox. We build Open Source software that supports Humanitarian Disaster Relief efforts. We'd appreciate any help you can give to our projects. Look at our GitHub home page to see a list of our current projects. See what interests you, and dive in.

Or, if you have a group of volunteers, talk to us about hosting a codeathon event.