Asynchronous programming is hard.

When coming from the iOS world, what you know are likely constructs like NSThread and Grand Central Dispatch to put off expensive work into a background thread or queue.

I've done a lot of work with C# recently in several Xamarin projects. Learning new languages is generally fun, but C# struck me especially with one detail: await. This one small yet powerful keyword is like a magic wand that cleans up code. The following three lines show a dialog, process a background operation and hide the dialog again. The snippet runs on the main thread.

var result = await expensiveMethod();

Even without knowing the context almost every developer will be able to recognize the intent behind these lines of code.

await is evaluated and processed by the compiler in a seperate stage and transformed into code that actually splits the method up into two parts, one is executed until the await keyword is encountered and the rest after the long running operation finished – with a completely restored environment, so your code doesn't even 'know' there was some waiting involved.

In order for a method to be awaitable, there's a second keyword, called async. both methods and lambdas can be async, but interestingly, async is not part of the method signature but merely a hint to the compiler. In practice, the expensiveMethod mentioned above would look something like this.

private async Task<string> expensiveMethod() {
    // e.g. download data 
    var returnValue = await httpClient.getAsync("");
    return returnValue;

Since under the hood, only Tasks can be awaited the return type in the signature has to be a Task for the whole construct to work – even though the value itself is returned in the method itself.

And that's how simple something rather complex like asynchronous programming can be. Of course, await and async are not the solution to every problem, but they certainly make some everyday tasks very easy to solve.

I can highly recommend Async in C# 5.0 for an in-depth discussion of that language feature.