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 应用于将并入消息的新答复通道,将生成消息。接收代理必须处理此消息并在此答复通道上正好调用一次 答复 方法。

示例

以下代码示例显示如何启动邮箱处理器代理。在此示例中,会将来自控制台的每行输入发布到消息队列中。程序读取每条消息,并通过答复通道进行答复。收到特别消息“停止”后,将发生停止回复并退出程序。

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,可移植

请参见

参考

Control.MailboxProcessor<'Msg> 类 (F#)

Microsoft.FSharp.Control 命名空间 (F#)