|
本文章是由機器翻譯。 將指標移到文章內的文字上方即可查看原文。 其他資訊。
|
譯文
原文
|
MailboxProcessor.Start<'Msg> 方法 (F#)
Visual Studio 2012
// Signature: static member Start : (MailboxProcessor<'Msg> -> Async<unit>) * ?CancellationToken -> MailboxProcessor<'Msg> // Usage: MailboxProcessor.Start (body) MailboxProcessor.Start (body, cancellationToken = cancellationToken)
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
信箱處理器測試類型一些文字並按 ENTER 送出訊息。
輸入 'Stop' 以關閉程式。
> Hello 1:主控台迴圈 4:mailboxProcessor 回覆:訊息編號 0 已收到。
訊息內容:Hello >測試 1:主控台迴圈 3:mailboxProcessor 回覆:訊息編號 1 已收到。
訊息內容:測試> Hello?
1:主控台迴圈 4:mailboxProcessor 回覆:訊息編號 2 已收到。
訊息內容:hello?
> 測試 1 2 3 1:主控台迴圈 3:mailboxProcessor 回覆:訊息編號 3 已收到。
訊息內容:測試 1 2 3 >停駐點 1:主控台迴圈 4:mailboxProcessor 按 ENTER 會繼續進行。