async/await part 1: Understanding the async keyword

By far my favorite feature of .NET 4.5 is async/await, or, as Microsoft call it, the Task-based Asynchronous Pattern (TAP). It is something I didn’t know I was missing until I saw a recording of Anders Hejlsberg’s Build talk on the subject. Shortly after this, I had a highly asynchronous C++ embedded project that lasted for over a year where I felt miserable building state machine after state machine to handle the inherent problem of all asynchronous programs: What do you do after your asynchronous operation completes?

This blog series is aimed at C# programmers new to async/await. A general understanding of the Task class introduced with .NET 4.0 is expected. In this first part, I’ll explain the async in async/await.

What is async?

The async keyword can be used to decorate a method or lambda expression.

It is important to note that async is not a part of the method signature, so if you are implementing an interface or overriding a virtual or abstract method you have a choice of whether to use async or not.

Return types

An async method may only return void, Task or Task<T> for any concrete type T.

void as a return type should be avoided where possible and is generally only needed in event handlers, making the method a fire-and-forget method where the caller has no way of knowing when the call finished or failed.

If you write a method returning Task or Task<T> you should generally follow the convention of using the suffix Async in your method name to indicate that the method can be awaited (regardless of whether you method’s implementation uses async or not).

Task should be returned for methods that would, if they were synchronous methods, return void. Task<T> should be returned for methods that would otherwise return some type T (i.e., anything not void). Think of the Task as the object the caller can use to keep track of what ever happened to that asynchronous method he triggered.

What effect does async have?

Writing async will do two things to your method or lambda:

  1. It will allow you to write await in your method (see my next blog post in this series).
  2. If your return type is not void the compiler will automagically convert your return statement (or the missing return statement at the end of your method) into a Task<T> or Task.

For a method that does not contain any await calls, this means a completed Task will be returned without the need to explicitly specify this. For the above example this means it will behave exactly like this non-async version of it:

For a method that does contain an await in the executed path, the method will return a Task object that will turn to the IsCompleted state when the last awaited call has completed and the synchronous code following it (if any) has finished executing. (For more on this, read my next blog post in this series about the await keyword.)

Do I need async?

Methods containing only one await statement as the very last instruction in the method may generally be written without the async keyword. For example, the method

is equivalent to

Even though this yields the same result, the method declared as async seems to be the more readable version and has a slight runtime penalty. The other difference here is that if stream.FlushAsync() throws an exception and await is not used FlushTheStreamAsync() will not appear in the exception’s call stack (more on exceptions in the next blog post).

How does that help me?

As mentioned earlier, the returned Task object can be used to examine the state of the asynchronous call (still running? completed? failed? cancelled?). While this is possible using the various methods of the Task class, the easiest way to handle this is through the await keyword handled in the next blog post.

DWX14 Follow-up: Introduction to Xamarin and MvvmCross


At this year’s Developer Week in N├╝rnberg I held a talk on cross-platform development using Xamarin and MvvmCross. I had a lot of fun with the live coding and enjoyed answering the questions.

My slides can be found on Slideshare in English and German. The code from live coding I created with the big help of Ninja Coder is up on GitHub.

An in-app status bar for Xamarin.iOS and MvvmCross

For an iPad app for our customer Smart Enterprise Solutions we wanted to display multiple messages to the user. These messages were mainly feedback from a business logic layer that communicated with a backend. The messages should be visible inside the app. Some messages needed to be confirmed by the user while others needed to disappear after a defined timespan.

This final status bar looks like this:

StatusBar

The code is available at https://github.com/lothrop/StatusBar.iOS.

The status bar view is called StatusView. To use StatusView, use auto-layouts to snap it to the left, right and bottom of your screen. StatusView is backed by the ViewModel MessageViewModel. MessageViewModel contains an ObservableCollection<IMessageItem>. You can insert items at any point in the collection, remove items or move items within the collection.

For a usage example, take a look at the MainViewController.cs file.

A big thanks to Smart Enterprise Solutions for letting me publish the code.

DWX13 Follow-up: Detecting jumps with Kinect and Reactive Extensions

At Developer Week 2013 I gave a talk (in German) on Reactive Extensions. The slides are online on Slideshare. During the talk, I live-coded a part of a console-based jump and run game that uses Kinect as input. The first task was to detect when the player (the volunteer on stage) jumped. Here’s the code from the demo:

This code contains a lot of simplifications for presentation purposes but it can still be used to explain some Reactive Extension concepts. I’ll walk you through it and also spell out the vars:

This retrieves the single Kinect that is attached to the PC (or throws an exception if there is not exactly one Kinect connected).

This creates an IObservable from the classic .NET event SkeletonFrameReady by telling Rx how to subscribe and unsubscribe from the event.

Interestingly, the class SkeletonFrameReadyEventArgs doesn’t contain any properties at all, just one method public SkeletonFrame OpenSkeletonFrame(); that can be used to access the skeleton data. The SkeletonFrame instance must then be disposed within 1/30 second.

We now have an IObservable that publishes a list of skeletons whenever there are people in front of the Kinect sensor.

This code extracts the joints from the single skeleton if it has a tracked state.

This extracts the average vertical position of the left and right foot. This is a simplification as it would be possible to trick the algorithm by just lifting one foot up twice as high as both feet would need to jump up. To fix this, you could Select() both feet in this statement.

This is the actual jump detection code. The idea is that to have jumped, the player would have to have his feet low, then high and then low again in a short timespan. To analyze this, we’re looking at samples from a time frame of one second. After this, we’ll move forward by 200 milliseconds and analyze again. This magic is provided by the Buffer() extension method. We’ll look for the maximum height of the feet within the time frame and see if the first and last samples are both lower than the maximum minus a hard-coded magic number (for simplification again). If the algorithm matches, the IObservable outputs the string “jumped”, else the string “didn’t jump”.

If you add jumped.Subscribe(Console.WriteLine); at this point you will see a stream of “didn’t jump” interrupted by a few instances of “jumped” whenever the player jumped.

The call to DistinctUntilChanged() will only output the string if it differs from the previously output string. The next line simply filters to only output “jumped” whenever the player jumps.

This line will output the resulting IObservable to the console.

This starts the Kinect sensor.

The presentation was a lot of fun. Thanks again to the volunteer! I’ll be back at Developer Week again this year talking about cross-platform mobile using C#.

Animation fun with UIView.AnimateAsync()

Xamarin.iOS 6.4 brought async/await support to iOS devices. Apart from supporting the idiom with the Mono 3.0 compiler, Xamarin also invested into adding awaitable versions of all long-running calls in Apple’s iOS API. One of my favorites is

UIView.AnimateAsync()

taking an Action or lambda to animate asynchronously without blocking the UI thread.

The fun begins when you use this to chain animations. Here’s an example of doing a horizontal shake animation that could be used to indicate an invalid entry: