Partilhar via


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

Assim como MailboxProcessor.PostAndReply, mas retorna None se não houver nenhuma desposta dentro do tempo limite.

Caminho do namespace/módulo: Microsoft.FSharp.Control

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

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

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

Parâmetros

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

    A função a incorporar o AsyncReplyChannel na mensagem a ser enviada.

  • timeout
    Tipo: int

    Um parâmetro de tempo limite opcional (em milissegundos) para aguardar uma mensagem de resposta. É padronizado para -1 que corresponde a Infinite.

Valor de retorno

A resposta do agente ou None se o tempo limite expirar.

Exemplo

O exemplo a seguir mostra como usar TryPostAndReply. Nesse exemplo, o agente tem um atraso que resulta eventualmente em um tempo limite.

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 will trigger 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)

let asyncReadInput =
   async {
       printf "> " 
       let input = Console.ReadLine();
       return input
   }

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() =
    Async.StartWithContinuations(asyncReadInput, (fun input ->
        let reply = agent.TryPostAndReply((fun replyChannel -> input, replyChannel), 1000)
        match reply with
        | None -> printfn "Timeout exceeded."
        | Some(reply) ->
            if (reply <> "Stop") then
                printfn "Reply: %s" reply
                loop()
            else
                ()),
        (fun exn -> ()),
        (fun _ -> ()))
loop()

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

Segue uma sessão de exemplo.

                   

Plataformas

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

Informações de versão

Versões da biblioteca principal F#

Suportado em: 2.0, 4.0, Portátil

Consulte também

Referência

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

Namespace Microsoft.FSharp.Control (F#)