You are previewing Programming F#.

Programming F#

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

Custom Computation Expression Builders

Now you have the capability to customize how various language constructs get executed by defining extra work to be carried out. But when would this be useful? It is clear that F# workflows were helpful when trying to determine the success or failure of a computation, but you might be skeptical that the same technique can make asynchronous programming easier.

Asynchronous Workflows

Think about the most tedious aspects of parallel and asynchronous programming—dealing with threads. If you want your program to have two things going on at once, you need to spawn new threads, give them appropriate work, and then marshal their results back. It is just as painful to exploit IO-level parallelism. The .NET Framework provides asynchronous IO operations via FileStream.BeginRead and FileStream.BeginWrite. However, using these constructs requires a messy combination of IAsyncResult interfaces, AsyncCallback delegates, and a lot of tedious code.

Even if you didn’t mind handling all the thread hopping and the managing of incomplete tasks yourself, it is still a pain to deal with exceptions. In addition, there is no good way to cancel the operation once it starts.

If only there were a way to abstract the code and wire in the thread hopping.... Fortunately, this library does exist and it is built into F#. F# asynchronous workflows are a type of computation expression builder specifically designed for asynchronous tasks.

Example 10-6 shows how to use an asynchronous ...

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