Asynchronous work flows are a very powerful tool in programming. They allow your threads to do other work while you wait for results from a long running piece of work. How would you write an asynchronous work flow in C#? Logically you might consider chaining together callbacks.
new Client().Connect(settings, (c1, ex1) => {
// prepare data to send
c.Send(sendData1, (c2, ex2) => {
c2.Receive((c3, dt1, ex3) => {
// parse data and prepare response
c3.Send(sendData2, (c4, ex4) => {
c4.Disconnect((c5, ex5) => {
c5.Dispose();
});
});
});
});
});
There is a good reason you never see code like this. For one, it is highly indented and this makes it a bit awkward to read. More importantly, this approach puts your code at risk of a great deal of name conflicts, as the compiler will create a closure for each lambda and capture all of the values in the previous levels. This means you have to come up with a different name for the parameters in each lambda. Resolving this issue could involve creating an additional class to contain the necessary methods, potentially complicating a task that seems like it should be simple. This is where F# asynchronous work flows come to play.
async {
try
use client = new Client()
do! client.Connect settings
// prepare data to send
do! client.Send sendData1
let! dt1 = client.Receive ()
// parse data and prepare response
do! client.Send sendData2
do! client.Disconnect ()
with
| ex ->
// handle exception
} |> Asnyc.Start // run in the thread pool
This is almost a literal translation of the C# except for one thing. Notice how the C# version threads through an exception parameter? In F# you have first class error handling in asynchronous work flows so the first failure will will call your exception handling code.
The first class support for asynchronous work flows is an amazing feature of F#. It allows you to create simple elegant code right where you need it. Think about some of your synchronous projects that just don't have the performance you need and consider F# as a powerful solution to you problem.

LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.