Compartir a través de


MailboxProcessor.PostAndTryAsyncReply<'Msg,'Reply> (Método de F#)

Como MailboxProcessor.AsyncPostAndReply, pero devuelve None si no se produce ninguna respuesta dentro del plazo del tiempo de espera.

Espacio de nombres/Ruta de acceso del módulo: Microsoft.FSharp.Control

Ensamblado: FSharp.Core (en FSharp.Core.dll)

// Signature:
member this.PostAndTryAsyncReply : (AsyncReplyChannel<'Reply> -> 'Msg) * ?int -> Async<'Reply option>

// Usage:
mailboxProcessor.PostAndTryAsyncReply (buildMessage)
mailboxProcessor.PostAndTryAsyncReply (buildMessage, timeout = timeout)

Parámetros

  • buildMessage
    Tipo: AsyncReplyChannel<'Reply> -> 'Msg

    Función que se usa para incorporar AsyncReplyChannel en el mensaje que se va a enviar.

  • timeout
    Tipo: int

    Parámetro de tiempo de espera opcional (en milisegundos) durante el cual se va a esperar un mensaje de respuesta. El valor predeterminado es -1, lo que corresponde a Infinite.

Valor devuelto

Cálculo asincrónico (objeto Async) que devolverá la respuesta o None si expira el tiempo de espera.

Ejemplo

En el código siguiente se muestra cómo puede utilizar el método PostAndTryAsyncReply.

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();
            // The delay gets longer with each message, and eventually triggers a timeout. 
            do! Async.Sleep(200 * n );
            if (message = "Stop") then
                replyChannel.Reply("Stop")
            else
                replyChannel.Reply(String.Format(formatString, n, message))
            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 mutable isCompleted = false 
while (not isCompleted) do
    printf "> " 
    let input = Console.ReadLine()
    let messageAsync = agent.PostAndTryAsyncReply((fun replyChannel -> input, replyChannel), 1000)
    // Set up a continuation function (the first argument below) that prints the reply. 
    // The second argument is the exception continuation. 
    // The third argument is the cancellation continuation (not used).
    Async.StartWithContinuations(messageAsync, 
         (fun reply -> 
             match reply with
             | None -> printfn "Reply timeout exceeded."
             | Some reply -> if (reply = "Stop") then
                                 isCompleted <- true 
                             else printfn "%s" reply),
         (fun exn ->
            printfn "Exception occurred: %s" exn.Message),
         (fun _ -> ()))

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

A continuación se muestra una sesión de ejemplo.

                   

Plataformas

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

Información de versiones

Versiones de la biblioteca básica de F#

Se admite en las versiones: 2.0, 4.0, Portable

Vea también

Referencia

Control.MailboxProcessor<'Msg> (Clase de F#)

Microsoft.FSharp.Control (Espacio de nombres de F#)