我正在尝试使用MailboxProcessor对异步作业处理框架进行建模。我的要求是启动、停止、暂停和恢复job processor。我能用MailboxProcessor构建暂停/恢复功能吗?另外,我应该能够停止和开始吗?我正在尝试模仿Windows服务。
我有一个用C#编写的系统,使用队列/线程实现。我正在寻找设计替代方案,就在那时我看到了MailboxProcessor。我相信我可以使用它,但是我不知道如何处理上面的场景。那么实现这一功能是可能的吗?
发布于 2009-06-25 04:13:39
当然:)只需保存一个内部作业队列,并在job processor处于启动模式时枚举该队列。在任何其他模式下,只需将新作业排入队列,直到处理器进入启动模式。
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停止,它就不能重新启动,排队的作业也不会运行(更改此行为很容易,这样就不会终止队列,只是不会将处于停止状态的作业排入队列)。
如果需要邮箱处理器和代码之间的双向通信,请使用MailboxProcessor.PostAndReply。
发布于 2009-06-25 06:37:08
你可能想看看Luca's blog,因为我认为它有some recent relevant stuff。
https://stackoverflow.com/questions/1041195
复制相似问题