在 C# ReceiveActor
s 我可以将状态作为类中的私有(private)字段。我应该如何使用 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 定义为一个尾递归函数,该函数以一些新状态调用自身。这是一个例子
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
关于f# - 如何在 F# Akka.NET Actor 中存储状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29100748/