MailboxProcessor.PostAndTryAsyncReply<'Msg,'Reply> 方法 (F#)
更新:2011 年 1 月
的 MailboxProcessor.AsyncPostAndReply,類似但傳回 None如果沒有回覆中的逾時期間。
命名空間/模組路徑: Microsoft.FSharp.Control
組件:FSharp.Core (在 FSharp.Core.dll 中)
// Signature:
member this.PostAndTryAsyncReply : (AsyncReplyChannel<'Reply> -> 'Msg) * ?int -> Async<'Reply option>
// Usage:
mailboxProcessor.PostAndTryAsyncReply (buildMessage)
mailboxProcessor.PostAndTryAsyncReply (buildMessage, timeout = timeout)
參數
buildMessage
型別:AsyncReplyChannel<'Reply> -> 'Msg的 AsyncReplyChannel 併入要傳送訊息至函式。
timeout
型別:int等待回應訊息的選擇性逾時參數 (以毫秒為單位)。 預設值為-1 會對應到 Infinite()
傳回值
會傳回回覆或 的非同步計算 ( 非同步 物件) None如果在逾時到期
範例
下列程式碼將示範如何使用 PostAndTryAsyncReply 方法。
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();
// The delay gets longer with each message, and eventually triggers a timeout.
do! Async.Sleep(200 * n );
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 messageAsync = agent.PostAndTryAsyncReply((fun replyChannel -> input, replyChannel), 1000)
// Set up a continuation function (the first argument below) that prints the reply.
// The second argument is the exception continuation.
// The third argument is the cancellation continuation (not used).
Async.StartWithContinuations(messageAsync,
(fun reply ->
match reply with
| None -> printfn "Reply timeout exceeded."
| Some reply -> if (reply = "Stop") then
isCompleted <- true
else printfn "%s" reply),
(fun exn ->
printfn "Exception occurred: %s" exn.Message),
(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 月 |
加入程式碼範例。 |
資訊加強。 |