Share via


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, Scan 또는 TryScan에 대한 둘 이상의 동시 호출이 활성화될 수 없습니다.

예제

다음 예제에서는 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# Core 라이브러리 버전

2.0, 4.0, 노트북 지원

참고 항목

참조

Control.MailboxProcessor<'Msg> 클래스(F#)

Microsoft.FSharp.Control 네임스페이스(F#)