Await anything – A tale about asynchronity

As most people who do any .NET related programming probably know, a short while ago, the next major version of the .NET framework and the tools that goes with it was released. This includes (but may not be limited to) Visual Studio 2012, .NET 4.5 and C# 4.5. One of the major new features of the .NET framework is its new support for async programming. Now, async programming has always (or rather, for as long as I can remember having wanted to do anything async) existed. For instance, if you create a Socket-instance, you have “BeginReceive” and “EndReceive” which provides asynchronous capability, however using them can be cumbersome. Normally you need a class to keep track of state, or you end up with a bunch of closures (given that you have .NET which is new enough to support closures). What this new capability does is to make it easy to create asynchronous code, and it generally does so with the help of Tasks.

Now, Tasks (System.Threading.Tasks.Task) have existed in .NET for a while, and I’ve used them for a while, cause I find they provide a simpler way of chaining calls one after another. For me, which have done most of my work in javascript, the ContinueWith<TIn, TResult>(Func<Task<TIn>, TResult>) feels natural, and easy to use. Handling completion-events is much more cumbersome for me. However, with .NET 4.5 the use of Tasks has been simplified even more, and of-cause I’m talking about the async and await keywords. However, I’m not going to explain how to create async functions, how these functions return Tasks, and what are great about them, cause there are probably already a thousand other post explaining this, what I want to look at more in-depth is the await keyword itself.


My quest for answers with regards to the await-keywords starts with the new release of Reactive Extensions. Reactive Extensions mainly does it’s work with a single interface; “IObservable<T>”. Now, because this is an interface, there is no way (that I know of) it could implement Task<T>. Neither, does (as far as I know) Task<T> implement IObservable<T>, meaning there is no connection between them what so ever. Here you might probably wonder why I’m stressing this out, and the reason for that is rather simple. While writing code working with IObservable<T>, Visual Studio kept telling me how IObservable<T> was awaitable! In other words, I could write await in front of any instance of IObservable<T>!
How could this be? Certainly, as I just explained, there is no connection between IObservable<T> and Task<T>. The answer, has to do with awaiters.

Awaiters, as I found after some googling, turns out to be one of the most curious compiler-patterns I’ve ever seen. From what I understand, for a type (lets call the instance myWait for now) to be awaitable, the following must be true:

  1. myWait.GetAwaiter() must be a valid expression
  2. myWait.GetAwaiter().IsCompleted must be a bool-property that is gettable, and returns a value indicating weather or not myWait is completed.
  3. myWait.GetAwaiter().GetResult() must be a valid expression, and must be a method that returns the result of the async operation, in other words, the result of “(await myWait)”.
  4. myWait.GetAwaiter().OnCompleted(Action continuation) must be a valid method that takes a single Action and quest that method for execution when the async operation is finnished.

Notice that I’ve stated that myWait.GetAwaiter must be a valid expression? What I find curious about this, is that it must be a valid expression for the compiler, not a valid method of myWait. In other words, GetAwaiter can be an extension method! This makes it possible to do some rather absurd things with await like await a TimeSpan (to delay the current execution), given that you provide a one-line extension-method for TimeSpan. More about this can be found here:


Last in this article I’d like to say a few words about a small project of mine, named SpotiFire. SpotiFire is a wrapper around the libspotify API’s, that makes it fairly easy for a .NET application to interact with spotify. The last update to SpotiFire (uploaded today) enables the use of async for a lot of operations. Here is a simple sample showing how easy some of the operations that used to be hard to do is:

About these ads

11 thoughts on “Await anything – A tale about asynchronity

  1. Have you ever considered about including a little bit more than just your articles?

    I mean, what you say is valuable and everything. But think of if you added some great graphics or videos to give your posts more, “pop”!
    Your content is excellent but with images and video clips, this site could
    definitely be one of the very best in its field. Terrific blog!

    • Sure I’ve considered. I’ve been planing on doing some video sometime, but there are a few problems with it. First of all, I’m not a native English speaker. Also I would have to design a presentation (something I’m not very good at). As with regards to images, some of the posts do contain that. It depends a bit on what I’m writing about, and when I’m doing it. Some of these posts takes a few days to write (not entire days ofcause, but they are spread over several days), and some are just thrown together in half an hour. The amount of work that goes into the posts vary depending on it’s content, and what I’m working on at the time. For instance, when I wrote this post, I just discovered what I was writing, and was at the same time working on implementing this into my own projects. So I set aside a little time to write this out in hope that it might help some peoples, and got back to work. And maybe I should have come back later to insert some graphics or maybe even a video, but I never got around to it.

      Also, these blogposts are mostly written for my own sake, because I feel like it. And if you find them useful I’m happy, but I have way too much stuff I want to make to invest a LOT of time into this blog, so sorry about that :)

  2. Fantastic beat ! I would like to apprentice while you
    amend your website, how can i subscribe for a blog site? The account helped me a acceptable deal.
    I had been a little bit acquainted of this your broadcast provided bright clear idea

    • I’m sorry, but I don’t know the inner workings of wordpress. I normally use RSS to follow blogs (using feedly as a RSS reader), though that requires one to manually check feedly from time to time (I check it all the time since I follow lots of blogs and other stuff).

    • Actually, this is a standard blog. The appearance is also a standard theme availible for wordpress. It’s named Dusk To Dawn by Automattic, and can be found in the theme-chooser of wordpress I believe (at least that’s where I found it a year or so ago).

  3. Hi Aleksander, regarding the implementation of GetAwaiter, the C# compiler is littered with these patterns. The compiler minimises the reliance on well known types for “syntactic sugar” implementations. If you look at LINQ, there is no dependency on IQueryable or IEnumerable in the compiler’s interpretation of where, select etc. You can just implement a method or extension method that has the same signature as Where(Func) or Select(Funct and it will allow the author to use the shorthand syntax. This is how shorthand syntax in Rx was possible. In my opinion, this is one of the most amazing things about the C# implementation.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s