在C#中,ReceiveActor
我可以将状态作为类中的私有字段。如何使用F#API以惯用的方式执行此操作?
这是一个好主意吗?还有其他选择吗?
let handleMessage (mailbox: Actor<'a>) msg =
let mutable i = 1
match msg with
| Some x -> i <- i + x
| None -> ()
您提出的方法完全适合作为在参与者中存储状态的一种方式。任何时候仅处理1条消息的并发性约束意味着,由于共享内存位置上的争用,不可能进入无效状态。
但是,这不是最惯用的选择。Akka.Net提供了一个F#API,以与F#MailboxProcessors类似的方式与actor一起工作。在这种情况下,您将actor定义为尾递归函数,该函数以某种新状态调用自身。这是一个例子
spawn system "hello" <|
fun mailbox ->
let rec loop state =
actor {
let! msg = mailbox.Receive ()
printfn "Received %A. Now received %s messages" msg state
return! loop (state + 1) //Increment a counter for the number of times the actor has received a message
}
loop 0
有关Akka.Net F#API的完整文档,请参见http://getakka.net/wiki/FSharp%20API
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句