共用方式為


MailboxProcessor.PostAndReply<'Msg,'Reply> 方法 (F#)

同步將訊息發佈至代理程式,並在通道上等待回覆。

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

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

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

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

參數

  • buildMessage
    型別:AsyncReplyChannel<'Reply> -> 'Msg

    用來將 AsyncReplyChannel 加入至要傳送之訊息的函式。

  • timeout
    型別:int

    等待回應訊息的選擇性逾時參數 (以毫秒為單位)。 預設為 -1,對應至 Infinite。

傳回值

代理程式的回覆。

備註

將 buildMessage 套用至要併入訊息中的新回覆通道,就會產生訊息。 接收代理程式必須處理這個訊息,而且只能在這個回覆通道上叫用一次 Reply 方法。

範例

下列程式碼範例示範如何啟動信箱處理器代理程式。 在此範例中,主控台輸入的每一行將被發送到訊息佇列中。 程式會讀取每個訊息,並使用回覆通道回覆。 當收到「停止」訊息時,就會傳送停止回覆並結束程式。

open System

type Message = string * AsyncReplyChannel<string>

let formatString = "Message number {0} was received. Message contents: {1}"

let printThreadId note =

    // Append the thread ID.
    printfn "%d : %s" System.Threading.Thread.CurrentThread.ManagedThreadId note


let agent = MailboxProcessor<Message>.Start(fun inbox ->
    let rec loop n =
        async {
                let! (message, replyChannel) = inbox.Receive();
                printThreadId "MailboxProcessor"
                if (message = "Stop") then
                    replyChannel.Reply("Stopping.")
                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 rec loop() =
    printf "> "
    let input = Console.ReadLine()
    printThreadId("Console loop")
    let reply = agent.PostAndReply(fun replyChannel -> input, replyChannel)
    if (reply <> "Stopping.") then
        printfn "Reply: %s" reply
        loop()
    else
        ()
loop()

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

下列為範例工作階段。

  
  
  
  
  
  
  
  
  

平台

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