MailboxProcessor.PostAndTryAsyncReply<'Msg,'Reply> メソッド (F#)

更新 : 2011 年 1 月

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

    応答メッセージを待機するオプションのタイムアウト パラメーター (ミリ秒単位)。 既定値は Infinite() に対応する -1 です。

戻り値

タイムアウト時間が経過した場合に、応答または None を返す非同期計算 (Async オブジェクト)。

使用例

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 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#)

履歴の変更

日付

履歴

理由

2011 年 1 月

コード例を追加。

情報の拡充