MailboxProcessor.PostAndAsyncReply<'Msg,'Reply> 方法 (F#)
更新:2011 年 1 月
非同步將訊息發佈至代理程式,並在通道上等待回覆。
命名空間/模組路徑: 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()
傳回值
一個 asychronous 計算 ( 非同步 物件),將等待從代理程式回覆。
備註
將 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 7、Windows Vista SP2、Windows XP SP3、Windows XP x64 SP2、Windows Server 2008 R2、Windows Server 2008 SP2、Windows Server 2003 SP2
版本資訊
F# 執行階段
支援版本:2.0、4.0
Silverlight
支援版本:3
請參閱
參考
Control.MailboxProcessor<'Msg> 類別 (F#)
Microsoft.FSharp.Control 命名空間 (F#)
變更記錄
日期 |
History |
原因 |
---|---|---|
2011 年 1 月 |
加入程式碼範例。 |
資訊加強。 |