You are previewing Programming F#.

Programming F#

Cover of Programming F# by Chris Smith Published by O'Reilly Media, Inc.

Asynchronous Workflows

F# asynchronous workflows allow you to perform asynchronous operations without the need for explicit callbacks. So you can write the code as if it were using synchronous execution, but in actuality, the code will execute asynchronously, suspending and resuming the computation as asynchronous operations complete.


F# asynchronous workflows don’t introduce any new primitives to the .NET platform; rather, F#’s computation expression syntax makes the existing threading libraries much more palatable.

Example 11-6 repeats the same task of asynchronously reading and writing a file, except rather than using the APM, all of the asynchronous operations are handled by the F# asynchronous workflows library. The result is that the code is dramatically simpler to write and understand.

The magic of how async workflows works will be discussed shortly. But for now, just notice that the code is wrapped up in the async computation expression builder and the asynchronous operations begin with let! and do!. Also, note that the result of the async builder is passed to the mysterious Async.Start method.

Example 11-6. Asynchronous file IO using F# async workflows

open System.IO

let asyncProcessFile (filePath : string) (processBytes : byte[] -> byte[]) =
    async {

        printfn "Processing file [%s]" (Path.GetFileName(filePath))

        use fileStream = new FileStream(filePath, FileMode.Open)
        let bytesToRead = int fileStream.Length

        let! data = fileStream.AsyncRead(bytesToRead) printfn "Opened [%s], ...

The best content for your career. Discover unlimited learning on demand for around $1/day.