MailboxProcessor只是复制IObservable吗? [英] Does MailboxProcessor just duplicate IObservable?

查看:67
本文介绍了MailboxProcessor只是复制IObservable吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想处理消息的类型

添加x 使程序记住数字x

打印使其打印所有已记住的数字

Print makes it print all remembered numbers

我为什么要这样写:

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 .

The MailboxProcessor adds additional level of complexity. I need a state machine which takes a state and returns a state. But it forces me to take inbox, which is used to receive state.

IObservable 有什么优势吗?

推荐答案

不,它们不是彼此的重复项. MailboxProcessor IObservable 是两种不同的计算模型(分别是参与者模型和功能反应编程)的低级构建块.

No, they're not duplicates of one another. MailboxProcessor and IObservable are low-level building blocks of two different models of computation - actor model and functional reactive programming respectively.

两者都处理异步性,但要强调

Both deal with asynchronicity, but emphasize different qualities. It's might be possible to build your solution in terms of one or the other - as you noticed in your simple example - but you will find one or the other more natural to use in a particular context.

MailboxProcessors 对于线程安全,无锁访问资源(例如文件)特别有用.您可以有多个线程通过异步接口来操纵资源,并且 MailboxProcessor 保证一次仅处理其中一个请求.

MailboxProcessors are particularly useful for thread-safe, lock-free access to a resource, such as a file. You can have multiple threads manipulating the resource through an asynchronous interface, and the MailboxProcessor guarantees that only one of those requests is processed at a time.

这篇关于MailboxProcessor只是复制IObservable吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆