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

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。

返回值

一个将返回答复的异步计算(Async 对象),如果超时时间到期,则返回 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 8,Windows 7,Windows server 2012中,Windows server 2008 R2

版本信息

F#核心库版本

支持:2.0,4.0,可移植

请参见

参考

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

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