共用方式為


MailboxProcessor.TryReceive<'Msg> 方法 (F#)

等待訊息。 這將會使用第一個收到的訊息。

**命名空間/模組路徑:**Microsoft.FSharp.Control

組件:FSharp.Core (在 FSharp.Core.dll 中)

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

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

參數

  • timeout
    型別:int

    選擇性逾時 (以毫秒為單位)。 預設為 -1,對應至 Infinite。

傳回值

會傳回所接收訊息的非同步計算 (Async 物件),如果超出逾時值則傳回 None。

備註

這個方法要在代理程式的主體中使用。 如果指定逾時值,並超出逾時值,則傳回 None。 這個方法要在代理程式的主體中使用。 針對每個代理程式,最多可以有一個使用中並行閱讀器,所以 ReceiveTryReceiveScanTryScan 的使用中呼叫不能超過一個。

範例

下列範例顯示如何使用 TryReceive。 如果未在 10 秒鐘內收到訊息,就會發生逾時,並將訊息 ID 遞增 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! 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

範例工作階段如下。 請注意,由於逾時所以略過訊息 2。

  
  
  
  
  
  

平台

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

版本資訊

F# 核心程式庫版本

支援版本:2.0, 4.0,可攜式執行檔 (PE)。

請參閱

參考

Control.MailboxProcessor<'Msg> 類別 (F#)

Microsoft.FSharp.Control 命名空間 (F#)