Mastering F# by Alfonso Garcia-Caro Nunez & Suhaib Fahad

Mastering F# by Alfonso Garcia-Caro Nunez & Suhaib Fahad

Author:Alfonso Garcia-Caro Nunez & Suhaib Fahad [Nunez, Alfonso Garcia-Caro]
Language: eng
Format: mobi
Publisher: Packt Publishing
Published: 2016-11-29T16:00:00+00:00


Note

Note that you should always keep the reply channel as the last parameter in your union type definition.

To use this calculator agent, we will simply create an object and use the APIs that are exposed to us:

> let c = new CalculatorAgent();; > c.Add(10, 20);; val it : int = 30

Likewise, if we are inside an async block, then we can call the async functions to evaluate the results.

Agents and errors

Good error detection, reporting, and logging are essential in actor programming. Let's take a look at how to detect and forward errors when using F# mailbox processors.

F# async workflows catch exceptions and propagate them automatically within async { ... } blocks, even across async waits and I/O operations. You can also use try /with , try /finally , and use constructs within the async { ... } blocks to catch exceptions and release resources. This means that we will only need to deal with uncaught errors in agents. When an errors is uncaught in the MailboxProcessor class, the Error event on the agent is raised. A common pattern is to forward all errors to a supervising actor, as shown in the following code block:

let error_supervisor = MailboxProcessor<System.Exception>.Start(fun inbox -> async { while true do let! err = inbox.Receive() printfn "an error '%A' occurred in an agent" err }) let agent = new MailboxProcessor<int>(fun inbox -> async { while true do let! msg = inbox.Receive() if msg % 100 = 0 then failwith "I don't like that cookie!" }) agent.Error.Add(fun error -> error_supervisor.Post error) agent.Start()

The preceding example reports an error when we have received 100 messages. When executing the following error agent, MailboxProcessor does not have more supervision capabilities built in:

an error 'I don't like that cookie!' occurred in an agent

If we want more advanced functionality, for example, making the supervisor restart the failing actor, we will need to implement it ourselves. In Chapter 10 , Distributed Programming with F# , we will see how supervision is a central concept in another actor system implementation, Akka.NET.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.