MailboxProcessor.TryPostAndReply<'Msg,'Reply> 方法 (F#)

MailboxProcessor.PostAndReply 类似,但如果在超时期未回复,则返回 None。

命名空间/模块路径: Microsoft.FSharp.Control

程序集:FSharp.Core(在 FSharp.Core.dll 中)

// Signature:
member this.TryPostAndReply : (AsyncReplyChannel<'Reply> -> 'Msg) * ?int -> 'Reply option

// Usage:
mailboxProcessor.TryPostAndReply (buildMessage)
mailboxProcessor.TryPostAndReply (buildMessage, timeout = timeout)

参数

  • buildMessage
    类型:AsyncReplyChannel<'Reply> -> 'Msg

    要将 AsyncReplyChannel 并入要发送的消息的函数。

  • timeout
    类型:int

    用于等待答复消息的可选超时参数(以毫秒为单位)。默认值为 -1,它对应于 Infinite。

返回值

来自代理的答复;如果超时过期,则为 None。

示例

下面的示例显示如何使用 TryPostAndReply。在此示例中,代理包含的延迟甚至可导致超时。

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 will trigger 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)

let asyncReadInput =
   async {
       printf "> "
       let input = Console.ReadLine();
       return input
   }

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() =
    Async.StartWithContinuations(asyncReadInput, (fun input ->
        let reply = agent.TryPostAndReply((fun replyChannel -> input, replyChannel), 1000)
        match reply with
        | None -> printfn "Timeout exceeded."
        | Some(reply) ->
            if (reply <> "Stop") then
                printfn "Reply: %s" reply
                loop()
            else
                ()),
        (fun exn -> ()),
        (fun _ -> ()))
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#)