Table of contents
Collapse the table of content
Expand the table of content

MailboxProcessor.Receive<'Msg> Method (F#)

Den Delimarsky|Last Updated: 8/18/2017
1 Contributor

Waits for a message. This will consume the first message in arrival order.

Namespace/Module Path: Microsoft.FSharp.Control

Assembly: FSharp.Core (in FSharp.Core.dll)


// Signature:
member this.Receive : ?int -> Async<'Msg>

// Usage:
mailboxProcessor.Receive ()
mailboxProcessor.Receive (timeout = timeout)


timeout Type: int

An optional timeout in milliseconds. Defaults to -1 which corresponds to System.Threading.Timeout.Infinite.


TimeoutExceptionThrown when the timeout is exceeded.

Return Value

An asynchronous computation (Async object) that returns the received message.


This method is for use within the body of the agent. For each agent, at most one concurrent reader may be active, so no more than one concurrent call to Receive, TryReceive, Scan or TryScan may be active.


The following example shows how to use the Receive method. In this case, a timeout of 10 seconds is specified. In general, the message processing function runs on a different thread from the Post function, so you must catch the timeout exception in the message processor function. In this example, the timeout exception just causes the loop to continue, and increases the message number by 1.

open System

type Message = string * AsyncReplyChannel<string>

let formatString = "Message number {0} was received. Message contents: {1}"

let agent = MailboxProcessor<Message>.Start(fun inbox ->
    let rec loop n =
        async {            
                let! (message, replyChannel) = inbox.Receive(10000);
                if (message = "Stop") then
                    replyChannel.Reply(String.Format(formatString, n, message))
                do! loop (n + 1)
            | :? TimeoutException -> 
                printfn "The mailbox processor timed out."
                do! loop (n + 1)
    loop (0))

printfn "Mailbox Processor Test"
printfn "Type some text and press Enter to submit a message."
printfn "Type 'Stop' to close the program."

let rec loop() =
    printf "> "
    let input = Console.ReadLine()
    let reply = agent.PostAndReply(fun replyChannel -> input, replyChannel)
    if (reply <> "Stop") then
        printfn "Reply: %s" reply

printfn "Press Enter to continue."
Console.ReadLine() |> ignore

A typical session follows. Notice that message 2 is skipped, due to the timeout.

> hello
Reply: Message number 0 was received. Message contents: hello
> hello?
Reply: Message number 1 was received. Message contents: hello?
> The mailbox processor timed out.
anyone there?
Reply: Message number 3 was received. Message contents: anyone there?


Windows 8, Windows 7, Windows Server 2012, Windows Server 2008 R2

Version Information

F# Core Library Versions

Supported in: 2.0, 4.0, Portable

See Also

Control.MailboxProcessor<'Msg> Class (F#)

Microsoft.FSharp.Control Namespace (F#)

© 2020 Microsoft