Thursday, January 31, 2013

Book Review: Async in C# 5.0

I recently finished reading Async in C# 5.0 by Alex Davies (Amazon Link).  This is quite a short book (at 92 pages), but it contains quite a bit of useful information in that space.

The book covers that "async" and "await" keywords that were added in C# 5.0.  Because the new functionality is based around the Task Asynchronous Pattern (TAP), the book spends quite a bit of time talking about Tasks (which were added in C# 4.0).

With that said, if you are brand new to Tasks, then this book is probably not the best place to start.  It quickly covers the different asynchronous patterns that were available before async/await, but this is more of a reminder than an introduction.  There's not quite enough for someone who is not already familiar with these patterns.

The book has 15 chapters, which means that each chapter is fairly short (just 5 or 6 pages for many of them).  But there is enough information in each to be useful.  Some interesting examples include the following:
  • Writing Asynchronous Code Manually
  • Writing Async Methods
  • What await Actually Does
  • The Task-Based Asynchronous Pattern
  • Utilities for Async Code (including cancellation and progress reporting)
  • Exceptions in Async Code
  • Async in ASP.NET Applications
  • Async in WinRT Applications
An example of one of the shorter chapters is "Unit Testing Async Code".  This is just 2 pages long.  But in those two pages, it covers the problems with testing async code with a traditional unit test -- mainly, that since async methods return immediately, the test will actually complete before the asynchronous part is finished (and will always return "successful").  There are basically 2 approaches: (1) force the test code to run synchronously, or (2) let the unit test return a Task type (rather than void) -- MSTest (as well as some other testing frameworks) have been updated to support async tests that return Task.

In addition to showing how to use async and await in your own code, the book also covers some of the inner workings.  This includes a look at the methods that are generated by the compiler (with some simplified IL samples) and also how the stack is maintained and reported during debugging.

There are quite a few good tidbits -- such as how to create async wrapper methods to add functionality -- that make this book a good read.

It's short, it's cheap, and it contains quite a bit of useful information.  Well worth the read (especially useful is you've got a bit of Task-based programming under your belt).

Happy Coding!

No comments:

Post a Comment