共用方式為


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

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

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

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

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

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

參數

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

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

  • timeout
    型別:int

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

傳回值

非同步計算 (非同步物件),將等待來自代理程式的回覆。

備註

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

範例

下列程式碼範例顯示使用 PostAndAsyncReply 的信箱處理器代理程式。 PostAndAsyncReply 的傳回值是非同步工作流程,在本例中會使用 Async.StartWithContinuations 啟動此工作流程,以設定處理回覆的程式碼。

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();
                // Delay so that the responses come in a different order.
                do! Async.Sleep( 5000 - 1000 * n);
                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."

let isCompleted = false
while (not isCompleted) do
    printf "> "
    let input = Console.ReadLine()
    let messageAsync = agent.PostAndAsyncReply(fun replyChannel -> input, replyChannel)

    // Set up a continuation function (the first argument below) that prints the reply.
    // The second argument is the exception continuation (not used).
    // The third argument is the cancellation continuation (not used).
    Async.StartWithContinuations(messageAsync, 
         (fun reply -> printfn "%s" reply),
         (fun _ -> ()),
         (fun _ -> ()))

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