MailboxProcessor.TryReceive<'Msg> 方法 (F#)

等待消息。这将按到达顺序使用第一条消息。

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

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

// Signature:
member this.TryReceive : ?int -> Async<'Msg option>

// Usage:
mailboxProcessor.TryReceive ()
mailboxProcessor.TryReceive (timeout = timeout)

参数

  • timeout
    类型:int

    可选超时(以毫秒为单位)。默认值为 -1,它对应于 Infinite。

返回值

一个返回收到的消息的异步计算 (Async 对象),如果超时时间已过则返回 None。

备注

此方法可在代理的主体内使用。如果给定超时并超过超时,则返回 None。此方法可在代理的主体内使用。对于每个代理,至多只有一个并发读线程可处于活动状态,因此不能有多个对 Receive, TryReceive, ScanTryScan 的并发调用处于活动状态。

示例

下面的示例显示如何使用 TryReceive。如果在 10 秒钟内收不到一条消息,即超时发生并且消息 ID 增量为 1。

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! opt = inbox.TryReceive(10000);
                match opt with
                | None -> do! loop(n + 1)
                | Some (message, replyChannel) ->
                    // The delay gets longer with each message, and eventually triggers a timeout.
                    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 reply = agent.PostAndReply(fun replyChannel -> input, replyChannel)
    if (reply <> "Stop") then
        printfn "Reply: %s" reply
    else
        isCompleted <- true

printfn "Press Enter to continue."
Console.ReadLine() |> ignore

示例会话如下。请注意,由于超时,将跳过编号 2 的消息。

  
  
  
  
  
  

平台

Windows 8,Windows 7,Windows server 2012中,Windows server 2008 R2

版本信息

F#核心库版本

支持:2.0,4.0,可移植

请参见

参考

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

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