C# Async Examples in F# – Part 1

This post is the first of a series where I am converting the C# 101 Async Samples into F#. See below for the other entries in the series:

C# Async Examples in F# – Part 2

C# Async Examples in F# – Part 3

Some of you may be familiar with my boss and C# guru Bill Wagner’s series on Async Samples in C#. For those of you who aren’t familiar, he has been working through the 101 Async Samples and posting his comments for each sample. The series is well worth a look if you’re looking to learn about the upcoming async features of C#.

Starting with this post, I’ll also be working through the 101 Async Examples, but I’ll be re-writing them in F#. For each example, I’ll also briefly discuss the tradeoffs between the F# and C# async models. I think that it will be a fun way to compare the C# and F# examples, and I hope to learn a few things along the way. Maybe you will, too!

I’ll try to keep these posts on the short side (no promises), but if you want an in depth comparison of the C# and F# async models, I highly recommend this excellent series on Asynchronous C# and F# by Tomas Petricek.

With the intro out of the way, let’s take a look at the first sample which makes an asynchronous web request and outputs the result. In C# that looks like this:

public async void AsyncIntroSingle()
{
    WriteLinePageTitle(await new WebClient().DownloadStringTaskAsync(new Uri("http://www.weather.gov")));
}

And now the F# version:

let AsyncIntroSingle() =
    async {
        let client = new WebClient()
        let! result = client.AsyncDownloadString(Uri("http://www.weather.gov"))
        do WriteLinePageTitle(result)
    }
    |> Async.StartImmediate

The samples look different on first glance, but the structure is actually fairly similar if you work from the inside out. Both samples start with an extension to WebClient to perform an asynchronous web request. Next, a keyword is used to yield control flow while the async operation occurs. C# uses the await keyword to do this while F# uses let! (more on this later).  Finally, the result is passed to the WriteLinePageTitle function to print the result.

The outermost layer is where things start to differ. The C# version starts the async operation immediately, but the F# requires some extra work. This is one of the major differences between the C# and F# models. C# tasks start as soon as you create them, but F# requires you to manually start the task. For simple examples, this makes the C# version cleaner. However, the F# model gives you more power to compose tasks and decide how they will run.

The last thing that I will point out is F#’s async { } block vs the async keyword on the method signature in C#. These constructs both indicate that asynchronous operations will be performed within a context. In C# this context is a method, but in F# the context is a workflow. This seems like a minor point, but it hints at the significant difference in implementation between C# and F# async. Async in C# is implemented by the compiler, but F# async is not a special language hack. F# Computation Expressions (Monads) provide the underpinnings for the F# async model. An explanation of Computation Expressions is well beyond the scope of this post, but know that the same magic that makes the let! keyword perform async operations in this sample can be extended to do other powerful things (like building sequences) in F#.

This entry was posted in Async, C#, F#. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

4 Trackbacks

  1. [...] C# Async Examples in F# – Part 1 – Chris Marinos kicks off a series of posts looking at reformulating Bill Wagner’s 101 Async Samples from C# to F#, starting off with a simple example, and discussing some of the key implementation details of the F# version. [...]

  2. By Friday Links #165 | Blue Onion Software * on August 12, 2011 at 11:15 am

    [...] C# Async examples in F# – Part 1 | //TODO: – Chris Marinos' Blog Incandescent Software: A comprehensive list of resources about JavaScript Travis CI Wekeroad — The BackboneJS and Knockout Danceoff Introducing the Knockout.Unobtrusive Plugin | User InExperience [...]

  3. [...] //TODO: – Chris Marinos' Blog Skip to content AboutOpen Source « C# Async Examples in F# – Part 1 [...]

  4. [...] C# Async Examples in F# – Part 1 [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>