Condividi tramite


Metodo MailboxProcessor.Start<'Msg> (F#)

Crea e avvia un agente.

Percorso di spazio dei nomi/modulo: Microsoft.FSharp.Control

Assembly: FSharp.Core (in FSharp.Core.dll)

// Signature:
static member Start : (MailboxProcessor<'Msg> -> Async<unit>) * ?CancellationToken -> MailboxProcessor<'Msg>

// Usage:
MailboxProcessor.Start (body)
MailboxProcessor.Start (body, cancellationToken = cancellationToken)

Parametri

Valore restituito

L'oggetto MailboxProcessor creato.

Note

La funzione body viene utilizzata per generare il calcolo asincrono eseguito dall'agente.

Esempio

Nell'esempio di codice riportato di seguito viene illustrato come avviare un agente del processore della cassetta postale. In questo esempio, ogni linea di input dalla console viene inserita in una coda di messaggi. Il programma legge ogni messaggio e risponde tramite un canale di risposta. Quando si riceve il messaggio speciale "Stop", viene inviata la risposta Stop e si chiude il programma.

open System

type Message = string * AsyncReplyChannel<string>

let formatString = "Message number {0} was received. Message contents: {1}"

let printThreadId note =

    // Append the thread ID.
    printfn "%d : %s" System.Threading.Thread.CurrentThread.ManagedThreadId note


let agent = MailboxProcessor<Message>.Start(fun inbox ->
    let rec loop n =
        async {
                let! (message, replyChannel) = inbox.Receive();
                printThreadId "MailboxProcessor"
                if (message = "Stop") then
                    replyChannel.Reply("Stopping.")
                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 rec loop() =
    printf "> "
    let input = Console.ReadLine()
    printThreadId("Console loop")
    let reply = agent.PostAndReply(fun replyChannel -> input, replyChannel)
    if (reply <> "Stopping.") then
        printfn "Reply: %s" reply
        loop()
    else
        ()
loop()

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

Di seguito viene riportata una sessione di esempio.

                    

Piattaforme

Windows 7, Windows Vista SP2, Windows XP SP3, Windows XP x64 SP2, Windows Server 2008 R2, Windows Server 2008 SP2, Windows Server 2003 SP2.

Informazioni sulla versione

F# Runtime

Supportato in: 2.0, 4.0

Silverlight

Supportato in: 3

Vedere anche

Riferimenti

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

Spazio dei nomi Microsoft.FSharp.Control (F#)

Cronologia delle modifiche

Data

Cronologia

Motivo

Gennaio 2011

Aggiunto esempio di codice.

Miglioramento delle informazioni.