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.
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.BeginWrite. However, using these
constructs requires a messy combination of
AsyncCallback delegates, and a lot of tedious
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 ...