【问题标题】:Does MailboxProcessor just duplicate IObservable?MailboxProcessor 是否只是复制 IObservable?
【发布时间】:2016-07-30 07:17:32
【问题描述】:

我想处理消息的类型

Add x 让程序记住数字 x

Print 让它打印所有记住的数字

我为什么要写这个:

open System
type Message =
    | Add of int
    | Print
let mailbox = new MailboxProcessor<Message>(fun inbox -> 
        let rec loop history = async{
            let! msg=inbox.Receive()
            match msg with
                | Add x -> return! loop(history + x.ToString()+" ")
                | Print ->
                    printfn "%s" history
                    return! loop(history)
        }
        loop ""
    )
[<EntryPoint>]
let main argv = 
    mailbox.Start()
    mailbox.Post(Add 12)
    mailbox.Post(Add 56)
    mailbox.Post(Print)
    mailbox.Post(Add 34)
    mailbox.Post(Print)
    ignore <| Console.ReadLine()
    0

而不是这个:

open System
open System.Reactive.Subjects
type Message =
    | Add of int
    | Print
let subject = new Subject<Message>() 
[<EntryPoint>]
let main argv = 
    subject
        |> Observable.scan(fun history msg -> 
                match msg with
                        | Add x -> history + x.ToString()+" "
                        | Print ->
                            printfn "%s" history
                            history
            ) ""
        |> Observable.subscribe(fun _->())
        |> ignore
    subject.OnNext(Add 12)
    subject.OnNext(Add 56)
    subject.OnNext(Print)
    subject.OnNext(Add 34)
    subject.OnNext(Print)
    ignore <| Console.ReadLine()
    0

MailboxProcessor 增加了额外的复杂性。我需要一个状态机,它接受一个状态并返回一个状态。但它迫使我采取inbox,用于接收状态。

IObservable有什么好处吗?

【问题讨论】:

    标签: f# system.reactive actor


    【解决方案1】:

    不,它们不是相互重复的。 MailboxProcessorIObservable 是两种不同计算模型的低级构建块——分别是参与者模型和函数式反应式编程。

    两者都处理异步,但强调different qualities。正如您在简单示例中所注意到的那样,您可能会根据其中一种或另一种来构建您的解决方案,但您会发现在特定环境中使用其中一种更自然。

    MailboxProcessors 对于对资源(例如文件)的线程安全、无锁访问特别有用。您可以让多个线程通过异步接口操作资源,MailboxProcessor 保证一次只处理其中一个请求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多