共用方式為


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

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

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

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

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

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

參數

  • timeout
    型別:int

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

例外狀況

例外狀況

條件

TimeoutException

在超出逾時值時擲回。

傳回值

非同步計算 (Async 物件),傳回接收到的訊息。

備註

這個方法要在代理程式的主體中使用。 針對每個代理程式,最多可以有一個使用中並行閱讀器,所以 ReceiveTryReceiveScanTryScan 的使用中呼叫不能超過一個。

範例

下列範例示範如何使用 Receive 方法。 在這種情況下,指定 10 秒的逾時。 一般情況下,執行訊息處理函式的執行緒與 post 函式不同,因此您必須在訊息處理器函式中攔截逾時例外狀況。 在此範例中,逾時例外狀況只會導致迴圈繼續下去,並將訊息數量遞增 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 {            
            try
                let! (message, replyChannel) = inbox.Receive(10000);

                if (message = "Stop") then
                    replyChannel.Reply("Stop")
                else
                    replyChannel.Reply(String.Format(formatString, n, message))
                do! loop (n + 1)

            with
            | :? TimeoutException -> 
                printfn "The mailbox processor timed out."
                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 rec loop() =
    printf "> "
    let input = Console.ReadLine()
    let reply = agent.PostAndReply(fun replyChannel -> input, replyChannel)
    if (reply <> "Stop") then
        printfn "Reply: %s" reply
        loop()
    else
        ()
loop()

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#)