Async & Await in C# with Xamarin
One of the great things about the .NET Framework is that Microsoft has worked long and hard to improve many features. Since the initial release of .NET 1.0, there has been support for threading via .NET threads as well as an application-level threadpool. This provided a great starting point when compared to Visual Basic 6 and classic ASP programming. The release of.NET 4 brought significant improvements in the area of threading, asynchronous operations and parallel operations. While the improvements made working with asynchronous operations easier, new problems were introduced, since many of these operations work based on callbacks. For example:
- How should a developer handle error checking?
- The program flow tends to be non-linear. Fixing bugs can be problematic.
- It is hard for a developer to get an understanding of what is happening within an application.
The release of .NET 4.5 (and C# 5.0), in the fall of 2012, was a blockbuster update with regards to asynchronous operations and threads. Microsoft has added C# language keywords to take this non-linear callback-based program flow and turn it into a much more linear flow. Recently, Xamarin has updated Xamarin.Android and Xamarin.iOS to support async.
This article will look at how Xamarin has implemented the .NET 4.5/C# 5 support into their Xamarin.iOS and Xamarin.Android productions. There are three general areas that I'll focus on:
- A general look at the asynchronous support in Xamarin's mobile products. This includes async, await, and the implications that this has for cross-platform code.
- The new HttpClient class that is provided in .NET 4.5/Mono 3.2.
- Xamarin's extensions for asynchronous operations for Android and iOS.
FYI: Be aware that sometimes the OpenWeatherMap API breaks, for no reason. I found this out after I shipped the article in.