共用方式為


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

更新:2011 年 1 月

建立並啟動代理程式。

命名空間/模組路徑:Microsoft.FSharp.Control

組件:FSharp.Core (在 FSharp.Core.dll 中)

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

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

參數

傳回值

建立的 的 MailboxProcessor

備註

body 函式會用來產生由代理程式執行的非同步計算。

範例

下列程式碼範例會示範如何啟動信箱處理器代理程式。 在此的範例從主控台輸入的每一行張貼至訊息佇列中。 程式會讀取每一個訊息,並使用回覆通道回覆。 當收到特殊的 「 停止 」 訊息時,傳送停止回應,並關閉程式。

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

以下是一個範例工作階段。

                    

平台

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 月

加入程式碼範例。

資訊加強。