更新: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()。 
返回值
将等待来自代理的答复的异步计算(Async 对象)。
备注
通过将 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#)
修订记录
| Date | 修订记录 | 原因 | 
|---|---|---|
| 2011 年 1 月 | 添加了代码示例。 | 信息补充。 |