簡體   English   中英

如何使用MailboxProcessor創建作業隊列?

[英]How do I create a job queue using a MailboxProcessor?

我正在嘗試使用MailboxProcessor建模異步作業處理框架。 我的要求是啟動,停止,暫停和恢復作業處理器。 我可以使用MailboxProcessor構建暫停/恢復功能嗎? 我也應該能夠停下來開始嗎? 我試圖在Windows服務后建模。

我有一個C#系統,使用Queue / Threads實現。 我正在尋找設計替代品,就在我看到MailboxProcessor的時候。 我相信我可以使用它,但無法弄清楚如何處理上述情況。 那么有可能實現這個功能嗎?

當然:)只需保留一個內部作業隊列,並在作業處理器處於啟動模式時通過隊列進行枚舉。 在任何其他模式下,只需將新作業排入隊列,直到處理器進入啟動模式。

type 'a msg =       // '
    | Start
    | Stop
    | Pause
    | Job of (unit -> unit)

type processQueue() =        
    let mb = MailboxProcessor.Start(fun inbox ->
        let rec loop state (jobs : System.Collections.Generic.Queue<_>) =
            async {
                if state = Start then
                    while jobs.Count > 0 do
                        let f = jobs.Dequeue()
                        f()

                let! msg = inbox.Receive()
                match msg with
                | Start -> return! loop Start jobs
                | Pause -> return! loop Pause jobs
                | Job(f) -> jobs.Enqueue(f); return! loop state jobs
                | Stop -> return ()
            }
        loop Start (new System.Collections.Generic.Queue<_>()))

    member this.Resume() = mb.Post(Start)
    member this.Stop() = mb.Post(Stop)
    member this.Pause() = mb.Post(Pause)
    member this.QueueJob(f) = mb.Post(Job f)

此類的行為與預期的一樣:您可以將作業排入暫停狀態,但它們只能在“開始”狀態下運行。 一旦processQueue停止,它就無法重新啟動,並且所有排隊的作業都不會運行(它很容易改變這種行為,因此,它不會殺死隊列,而只是不會將作業排入Stop狀態)。

如果您需要郵箱處理器和代碼之間的雙向通信,請使用MailboxProcessor.PostAndReply

你可能想查看Luca的博客 ,因為我認為它有一些 最近的 相關 內容

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM