Share via


MailboxProcessor.TryReceive<'Msg>-Methode (F#)

Wartet auf eine Meldung.Die erste Meldung in der Reihenfolge des Eintreffens wird verarbeitet.

Namespace/Modulpfad: Microsoft.FSharp.Control

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

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

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

Parameter

  • timeout
    Typ: int

    Ein optionales Timeout in Millisekunden.Wird standardmäßig auf -1 festgelegt, was Infinite entspricht.

Rückgabewert

Eine asynchrone Berechnung (Asnyc-Objekt), die die empfangene Meldung oder None zurückgibt, wenn das Timeout überschritten wird.

Hinweise

Diese Methode ist für die Verwendung im Coderumpf des Agents vorgesehen.Gibt None zurück, wenn ein Timeout angegeben und das Timeout überschritten wird.Diese Methode ist für die Verwendung im Coderumpf des Agents vorgesehen.Für jeden Agent darf maximal ein Reader gleichzeitig aktiv sein. Es darf also nur maximal ein Aufruf von Receive, TryReceive, Scan oder TryScan aktiv sein.

Beispiel

Das folgende Beispiel veranschaulicht die Verwendung von TryReceive.Wenn eine Nachricht nicht innerhalb von 10 Sekunden empfangen wird, tritt ein Timeout auf und die Meldungs-ID wird um 1 erhöht.

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! opt = inbox.TryReceive(10000);
                match opt with
                | None -> do! loop(n + 1)
                | Some (message, replyChannel) ->
                    // The delay gets longer with each message, and eventually triggers a timeout.
                    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 reply = agent.PostAndReply(fun replyChannel -> input, replyChannel)
    if (reply <> "Stop") then
        printfn "Reply: %s" reply
    else
        isCompleted <- true

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

Eine Beispielsitzung folgt.Beachten Sie, dass die Meldungsnummer 2 aufgrund des Timeouts übersprungen wird.

  
  
  
  
  
  

Plattformen

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

Versionsinformationen

F#-Kern-Bibliotheks-Versionen

Unterstützt in: 2,0, 4,0, portablen

Siehe auch

Referenz

Control.MailboxProcessor<'Msg>-Klasse (F#)

Microsoft.FSharp.Control-Namespace (F#)