Udostępnij za pośrednictwem


MailboxProcessor.TryPostAndReply<'Msg,'Reply> — Metoda (F#)

Jak MailboxProcessor.PostAndReply, ale zwraca None jeśli brak odpowiedzi przed upływem limitu czasu.

Przestrzeń nazw/Ścieżka modułu: Microsoft.FSharp.Control

Zestaw: FSharp.Core (w FSharp.Core.dll)

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

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

Parametry

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

    Funkcja do włączenia AsyncReplyChannel do wiadomości do wysłania.

  • timeout
    Wpisz: int

    Opcjonalny parametr limitu czasu (w milisekundach) oczekujący na wiadomość odpowiedzi.Ustaw domyślnie na -1, co odnosi się do Infinite.

Wartość zwracana

Odpowiedź od agenta lub None jeżeli upłynie limit czasu.

Przykład

Poniższy przykład ilustruje sposób używania metody TryPostAndReply.W tym przykładzie, agent ma opóźnienie, które ostatecznie powoduje przekroczenie limitu czasu.

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

Następujące przykładowe sesji.

                 

Platformy

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

Informacje o wersji

Wersje podstawowe biblioteki języka F#

Obsługiwane przez: 2.0, 4.0, przenośne

Zobacz też

Informacje

Control.MailboxProcessor<'Msg> — Klasa (F#)

Microsoft.FSharp.Control — Przestrzeń nazw (F#)