How do I create a job queue using MailboxProcessor?

I am trying to simulate an asynchronous job processing structure using MailboxProcessor. My requirements are starting, stopping, pausing and resuming the job processor. Can I create Pause / Resume functions using MailboxProcessor? Also should I be able to stop and start? I am trying to simulate after a windows service.

I have a C # system implemented using Queue / Threads. I was looking for design alternatives when I saw the MailboxProcessor. I believe I can use it, but couldn't figure out how to deal with the above scenarios. So can this functionality be achieved?

+4


source to share


2 answers


Of course :) Just keep an internal job queue and enumerate through the queue when the job processor is in startup mode. In any other mode, just insert new jobs until the processor goes into startup mode.

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)

      



This class behaves as expected: you can define jobs in a paused state, but they will only work in a Start state. Once the processQueue is stopped, it cannot be restarted, and none of the jobs in the queue will be executed (it is easy enough to change this behavior so that instead of killing the queue, it simply does not put jobs in the Stop state).

Use MailboxProcessor.PostAndReply if you need two-way communication between the mailbox processor and your code.

+9


source


You might want to check out Luca's blog , as I think it has some latest relevant stuff .



+3


source







All Articles