共用方式為


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

更新:2011 年 1 月

等待訊息。 這將會使用第一個收到的訊息。

命名空間/模組路徑: 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()。

傳回值

傳回已接收的訊息或 的非同步計算 ( 非同步 物件) None如果超出逾時值

備註

這個方法要在代理程式的主體中使用。 傳回 None在指定逾時,而且在超過逾時如果 這個方法要在代理程式的主體中使用。 每一個的代理程式沒有多個並行 的 接收呼叫、 TryReceive掃描 TryScan 可能是使用中,因此可能使用中,最多一個的並行讀取器。

範例

下列範例顯示如何使用 TryReceive。 如果在 10 秒內未收到一則訊息,逾時,就會發生和訊息識別碼會加 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 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#)

變更記錄

日期

History

原因

2011 年 1 月

加入程式碼範例。

資訊加強。